babylon.max.js 4.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086
  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. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. var finalVertexCode;
  157. this._loadVertexShaderAsync(vertexSource)
  158. .then(function (vertexCode) {
  159. return _this._processIncludesAsync(vertexCode);
  160. })
  161. .then(function (vertexCodeWithIncludes) {
  162. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  163. return _this._loadFragmentShaderAsync(fragmentSource);
  164. })
  165. .then(function (fragmentCode) {
  166. return _this._processIncludesAsync(fragmentCode);
  167. })
  168. .then(function (fragmentCodeWithIncludes) {
  169. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  170. if (baseName) {
  171. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  172. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  173. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  174. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  175. }
  176. else {
  177. _this._vertexSourceCode = finalVertexCode;
  178. _this._fragmentSourceCode = migratedFragmentCode;
  179. }
  180. _this._prepareEffect();
  181. });
  182. }
  183. Object.defineProperty(Effect.prototype, "key", {
  184. get: function () {
  185. return this._key;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. // Properties
  191. Effect.prototype.isReady = function () {
  192. return this._isReady;
  193. };
  194. Effect.prototype.getEngine = function () {
  195. return this._engine;
  196. };
  197. Effect.prototype.getProgram = function () {
  198. return this._program;
  199. };
  200. Effect.prototype.getAttributesNames = function () {
  201. return this._attributesNames;
  202. };
  203. Effect.prototype.getAttributeLocation = function (index) {
  204. return this._attributes[index];
  205. };
  206. Effect.prototype.getAttributeLocationByName = function (name) {
  207. var index = this._attributesNames.indexOf(name);
  208. return this._attributes[index];
  209. };
  210. Effect.prototype.getAttributesCount = function () {
  211. return this._attributes.length;
  212. };
  213. Effect.prototype.getUniformIndex = function (uniformName) {
  214. return this._uniformsNames.indexOf(uniformName);
  215. };
  216. Effect.prototype.getUniform = function (uniformName) {
  217. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  218. };
  219. Effect.prototype.getSamplers = function () {
  220. return this._samplers;
  221. };
  222. Effect.prototype.getCompilationError = function () {
  223. return this._compilationError;
  224. };
  225. // Methods
  226. Effect.prototype.executeWhenCompiled = function (func) {
  227. if (this.isReady()) {
  228. func(this);
  229. return;
  230. }
  231. this.onCompileObservable.add(function (effect) {
  232. func(effect);
  233. });
  234. };
  235. /** @ignore */
  236. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  237. if (BABYLON.Tools.IsWindowObjectExist()) {
  238. // DOM element ?
  239. if (vertex instanceof HTMLElement) {
  240. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  241. return Promise.resolve(vertexCode);
  242. }
  243. }
  244. // Base64 encoded ?
  245. if (vertex.substr(0, 7) === "base64:") {
  246. var vertexBinary = window.atob(vertex.substr(7));
  247. return Promise.resolve(vertexBinary);
  248. }
  249. // Is in local store ?
  250. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  251. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  252. }
  253. var vertexShaderUrl;
  254. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  255. vertexShaderUrl = vertex;
  256. }
  257. else {
  258. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  259. }
  260. // Vertex shader
  261. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  262. };
  263. /** @ignore */
  264. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  265. if (BABYLON.Tools.IsWindowObjectExist()) {
  266. // DOM element ?
  267. if (fragment instanceof HTMLElement) {
  268. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  269. return Promise.resolve(fragmentCode);
  270. }
  271. }
  272. // Base64 encoded ?
  273. if (fragment.substr(0, 7) === "base64:") {
  274. var fragmentBinary = window.atob(fragment.substr(7));
  275. return Promise.resolve(fragmentBinary);
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  280. }
  281. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  282. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  283. }
  284. var fragmentShaderUrl;
  285. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  286. fragmentShaderUrl = fragment;
  287. }
  288. else {
  289. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  290. }
  291. // Fragment shader
  292. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  293. };
  294. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  295. // Rebuild shaders source code
  296. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  297. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  298. vertexCode = prefix + vertexCode;
  299. fragmentCode = prefix + fragmentCode;
  300. // Number lines of shaders source code
  301. var i = 2;
  302. var regex = /\n/gm;
  303. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  304. i = 2;
  305. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. // Dump shaders name and formatted source code
  307. if (this.name.vertexElement) {
  308. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  309. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  310. }
  311. else if (this.name.vertex) {
  312. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  313. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  314. }
  315. else {
  316. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  317. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  318. }
  319. };
  320. ;
  321. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  322. var preparedSourceCode = this._processPrecision(sourceCode);
  323. if (this._engine.webGLVersion == 1) {
  324. return preparedSourceCode;
  325. }
  326. // Already converted
  327. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  328. return preparedSourceCode.replace("#version 300 es", "");
  329. }
  330. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  331. // Remove extensions
  332. // #extension GL_OES_standard_derivatives : enable
  333. // #extension GL_EXT_shader_texture_lod : enable
  334. // #extension GL_EXT_frag_depth : enable
  335. // #extension GL_EXT_draw_buffers : require
  336. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  337. var result = preparedSourceCode.replace(regex, "");
  338. // Migrate to GLSL v300
  339. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  340. result = result.replace(/attribute[ \t]/g, "in ");
  341. result = result.replace(/[ \t]attribute/g, " in");
  342. if (isFragment) {
  343. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  344. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  345. result = result.replace(/texture2D\s*\(/g, "texture(");
  346. result = result.replace(/textureCube\s*\(/g, "texture(");
  347. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  348. result = result.replace(/gl_FragColor/g, "glFragColor");
  349. result = result.replace(/gl_FragData/g, "glFragData");
  350. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  351. }
  352. return result;
  353. };
  354. Effect.prototype._processIncludesAsync = function (sourceCode) {
  355. var _this = this;
  356. return new Promise(function (resolve, reject) {
  357. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  358. var match = regex.exec(sourceCode);
  359. var returnValue = sourceCode;
  360. while (match != null) {
  361. var includeFile = match[1];
  362. // Uniform declaration
  363. if (includeFile.indexOf("__decl__") !== -1) {
  364. includeFile = includeFile.replace(/__decl__/, "");
  365. if (_this._engine.supportsUniformBuffers) {
  366. includeFile = includeFile.replace(/Vertex/, "Ubo");
  367. includeFile = includeFile.replace(/Fragment/, "Ubo");
  368. }
  369. includeFile = includeFile + "Declaration";
  370. }
  371. if (Effect.IncludesShadersStore[includeFile]) {
  372. // Substitution
  373. var includeContent = Effect.IncludesShadersStore[includeFile];
  374. if (match[2]) {
  375. var splits = match[3].split(",");
  376. for (var index = 0; index < splits.length; index += 2) {
  377. var source = new RegExp(splits[index], "g");
  378. var dest = splits[index + 1];
  379. includeContent = includeContent.replace(source, dest);
  380. }
  381. }
  382. if (match[4]) {
  383. var indexString = match[5];
  384. if (indexString.indexOf("..") !== -1) {
  385. var indexSplits = indexString.split("..");
  386. var minIndex = parseInt(indexSplits[0]);
  387. var maxIndex = parseInt(indexSplits[1]);
  388. var sourceIncludeContent = includeContent.slice(0);
  389. includeContent = "";
  390. if (isNaN(maxIndex)) {
  391. maxIndex = _this._indexParameters[indexSplits[1]];
  392. }
  393. for (var i = minIndex; i < maxIndex; i++) {
  394. if (!_this._engine.supportsUniformBuffers) {
  395. // Ubo replacement
  396. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  397. return p1 + "{X}";
  398. });
  399. }
  400. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  401. }
  402. }
  403. else {
  404. if (!_this._engine.supportsUniformBuffers) {
  405. // Ubo replacement
  406. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  407. return p1 + "{X}";
  408. });
  409. }
  410. includeContent = includeContent.replace(/\{X\}/g, indexString);
  411. }
  412. }
  413. // Replace
  414. returnValue = returnValue.replace(match[0], includeContent);
  415. }
  416. else {
  417. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  418. _this._engine._loadFileAsync(includeShaderUrl)
  419. .then(function (fileContent) {
  420. Effect.IncludesShadersStore[includeFile] = fileContent;
  421. return _this._processIncludesAsync(returnValue);
  422. })
  423. .then(function (returnValue) {
  424. resolve(returnValue);
  425. });
  426. return;
  427. }
  428. match = regex.exec(sourceCode);
  429. }
  430. resolve(returnValue);
  431. });
  432. };
  433. Effect.prototype._processPrecision = function (source) {
  434. if (source.indexOf("precision highp float") === -1) {
  435. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  436. source = "precision mediump float;\n" + source;
  437. }
  438. else {
  439. source = "precision highp float;\n" + source;
  440. }
  441. }
  442. else {
  443. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  444. source = source.replace("precision highp float", "precision mediump float");
  445. }
  446. }
  447. return source;
  448. };
  449. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  450. var _this = this;
  451. this._isReady = false;
  452. this._vertexSourceCodeOverride = vertexSourceCode;
  453. this._fragmentSourceCodeOverride = fragmentSourceCode;
  454. this.onError = function (effect, error) {
  455. if (onError) {
  456. onError(error);
  457. }
  458. };
  459. this.onCompiled = function () {
  460. var scenes = _this.getEngine().scenes;
  461. for (var i = 0; i < scenes.length; i++) {
  462. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  463. }
  464. if (onCompiled) {
  465. onCompiled(_this._program);
  466. }
  467. };
  468. this._fallbacks = null;
  469. this._prepareEffect();
  470. };
  471. Effect.prototype.getSpecificUniformLocations = function (names) {
  472. var engine = this._engine;
  473. return engine.getUniforms(this._program, names);
  474. };
  475. Effect.prototype._prepareEffect = function () {
  476. var attributesNames = this._attributesNames;
  477. var defines = this.defines;
  478. var fallbacks = this._fallbacks;
  479. this._valueCache = {};
  480. var previousProgram = this._program;
  481. try {
  482. var engine = this._engine;
  483. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  484. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  485. }
  486. else {
  487. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  488. }
  489. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  490. if (engine.supportsUniformBuffers) {
  491. for (var name in this._uniformBuffersNames) {
  492. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  493. }
  494. }
  495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  496. this._attributes = engine.getAttributes(this._program, attributesNames);
  497. var index;
  498. for (index = 0; index < this._samplers.length; index++) {
  499. var sampler = this.getUniform(this._samplers[index]);
  500. if (sampler == null) {
  501. this._samplers.splice(index, 1);
  502. index--;
  503. }
  504. }
  505. engine.bindSamplers(this);
  506. this._compilationError = "";
  507. this._isReady = true;
  508. if (this.onCompiled) {
  509. this.onCompiled(this);
  510. }
  511. this.onCompileObservable.notifyObservers(this);
  512. this.onCompileObservable.clear();
  513. // Unbind mesh reference in fallbacks
  514. if (this._fallbacks) {
  515. this._fallbacks.unBindMesh();
  516. }
  517. if (previousProgram) {
  518. this.getEngine()._deleteProgram(previousProgram);
  519. }
  520. }
  521. catch (e) {
  522. this._compilationError = e.message;
  523. // Let's go through fallbacks then
  524. BABYLON.Tools.Error("Unable to compile effect:");
  525. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  526. return " " + uniform;
  527. }));
  528. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  529. return " " + attribute;
  530. }));
  531. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  532. BABYLON.Tools.Error("Error: " + this._compilationError);
  533. if (previousProgram) {
  534. this._program = previousProgram;
  535. this._isReady = true;
  536. if (this.onError) {
  537. this.onError(this, this._compilationError);
  538. }
  539. this.onErrorObservable.notifyObservers(this);
  540. }
  541. if (fallbacks && fallbacks.isMoreFallbacks) {
  542. BABYLON.Tools.Error("Trying next fallback.");
  543. this.defines = fallbacks.reduce(this.defines);
  544. this._prepareEffect();
  545. }
  546. else {
  547. if (this.onError) {
  548. this.onError(this, this._compilationError);
  549. }
  550. this.onErrorObservable.notifyObservers(this);
  551. this.onErrorObservable.clear();
  552. // Unbind mesh reference in fallbacks
  553. if (this._fallbacks) {
  554. this._fallbacks.unBindMesh();
  555. }
  556. }
  557. }
  558. };
  559. Object.defineProperty(Effect.prototype, "isSupported", {
  560. get: function () {
  561. return this._compilationError === "";
  562. },
  563. enumerable: true,
  564. configurable: true
  565. });
  566. Effect.prototype._bindTexture = function (channel, texture) {
  567. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  568. };
  569. Effect.prototype.setTexture = function (channel, texture) {
  570. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  571. };
  572. Effect.prototype.setTextureArray = function (channel, textures) {
  573. if (this._samplers.indexOf(channel + "Ex") === -1) {
  574. var initialPos = this._samplers.indexOf(channel);
  575. for (var index = 1; index < textures.length; index++) {
  576. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  577. }
  578. }
  579. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  580. };
  581. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  582. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  583. };
  584. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  585. var cache = this._valueCache[uniformName];
  586. var flag = matrix.updateFlag;
  587. if (cache !== undefined && cache === flag) {
  588. return false;
  589. }
  590. this._valueCache[uniformName] = flag;
  591. return true;
  592. };
  593. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  594. var cache = this._valueCache[uniformName];
  595. if (!cache) {
  596. cache = [x, y];
  597. this._valueCache[uniformName] = cache;
  598. return true;
  599. }
  600. var changed = false;
  601. if (cache[0] !== x) {
  602. cache[0] = x;
  603. changed = true;
  604. }
  605. if (cache[1] !== y) {
  606. cache[1] = y;
  607. changed = true;
  608. }
  609. return changed;
  610. };
  611. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  612. var cache = this._valueCache[uniformName];
  613. if (!cache) {
  614. cache = [x, y, z];
  615. this._valueCache[uniformName] = cache;
  616. return true;
  617. }
  618. var changed = false;
  619. if (cache[0] !== x) {
  620. cache[0] = x;
  621. changed = true;
  622. }
  623. if (cache[1] !== y) {
  624. cache[1] = y;
  625. changed = true;
  626. }
  627. if (cache[2] !== z) {
  628. cache[2] = z;
  629. changed = true;
  630. }
  631. return changed;
  632. };
  633. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  634. var cache = this._valueCache[uniformName];
  635. if (!cache) {
  636. cache = [x, y, z, w];
  637. this._valueCache[uniformName] = cache;
  638. return true;
  639. }
  640. var changed = false;
  641. if (cache[0] !== x) {
  642. cache[0] = x;
  643. changed = true;
  644. }
  645. if (cache[1] !== y) {
  646. cache[1] = y;
  647. changed = true;
  648. }
  649. if (cache[2] !== z) {
  650. cache[2] = z;
  651. changed = true;
  652. }
  653. if (cache[3] !== w) {
  654. cache[3] = w;
  655. changed = true;
  656. }
  657. return changed;
  658. };
  659. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  660. var bufferName = this._uniformBuffersNames[name];
  661. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  662. return;
  663. }
  664. Effect._baseCache[bufferName] = buffer;
  665. this._engine.bindUniformBufferBase(buffer, bufferName);
  666. };
  667. Effect.prototype.bindUniformBlock = function (blockName, index) {
  668. this._engine.bindUniformBlock(this._program, blockName, index);
  669. };
  670. Effect.prototype.setInt = function (uniformName, value) {
  671. var cache = this._valueCache[uniformName];
  672. if (cache !== undefined && cache === value)
  673. return this;
  674. this._valueCache[uniformName] = value;
  675. this._engine.setInt(this.getUniform(uniformName), value);
  676. return this;
  677. };
  678. Effect.prototype.setIntArray = function (uniformName, array) {
  679. this._valueCache[uniformName] = null;
  680. this._engine.setIntArray(this.getUniform(uniformName), array);
  681. return this;
  682. };
  683. Effect.prototype.setIntArray2 = function (uniformName, array) {
  684. this._valueCache[uniformName] = null;
  685. this._engine.setIntArray2(this.getUniform(uniformName), array);
  686. return this;
  687. };
  688. Effect.prototype.setIntArray3 = function (uniformName, array) {
  689. this._valueCache[uniformName] = null;
  690. this._engine.setIntArray3(this.getUniform(uniformName), array);
  691. return this;
  692. };
  693. Effect.prototype.setIntArray4 = function (uniformName, array) {
  694. this._valueCache[uniformName] = null;
  695. this._engine.setIntArray4(this.getUniform(uniformName), array);
  696. return this;
  697. };
  698. Effect.prototype.setFloatArray = function (uniformName, array) {
  699. this._valueCache[uniformName] = null;
  700. this._engine.setFloatArray(this.getUniform(uniformName), array);
  701. return this;
  702. };
  703. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  704. this._valueCache[uniformName] = null;
  705. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  706. return this;
  707. };
  708. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  709. this._valueCache[uniformName] = null;
  710. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  711. return this;
  712. };
  713. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  714. this._valueCache[uniformName] = null;
  715. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  716. return this;
  717. };
  718. Effect.prototype.setArray = function (uniformName, array) {
  719. this._valueCache[uniformName] = null;
  720. this._engine.setArray(this.getUniform(uniformName), array);
  721. return this;
  722. };
  723. Effect.prototype.setArray2 = function (uniformName, array) {
  724. this._valueCache[uniformName] = null;
  725. this._engine.setArray2(this.getUniform(uniformName), array);
  726. return this;
  727. };
  728. Effect.prototype.setArray3 = function (uniformName, array) {
  729. this._valueCache[uniformName] = null;
  730. this._engine.setArray3(this.getUniform(uniformName), array);
  731. return this;
  732. };
  733. Effect.prototype.setArray4 = function (uniformName, array) {
  734. this._valueCache[uniformName] = null;
  735. this._engine.setArray4(this.getUniform(uniformName), array);
  736. return this;
  737. };
  738. Effect.prototype.setMatrices = function (uniformName, matrices) {
  739. if (!matrices) {
  740. return this;
  741. }
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  744. return this;
  745. };
  746. Effect.prototype.setMatrix = function (uniformName, matrix) {
  747. if (this._cacheMatrix(uniformName, matrix)) {
  748. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  749. }
  750. return this;
  751. };
  752. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  753. this._valueCache[uniformName] = null;
  754. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  755. return this;
  756. };
  757. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  758. this._valueCache[uniformName] = null;
  759. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  760. return this;
  761. };
  762. Effect.prototype.setFloat = function (uniformName, value) {
  763. var cache = this._valueCache[uniformName];
  764. if (cache !== undefined && cache === value)
  765. return this;
  766. this._valueCache[uniformName] = value;
  767. this._engine.setFloat(this.getUniform(uniformName), value);
  768. return this;
  769. };
  770. Effect.prototype.setBool = function (uniformName, bool) {
  771. var cache = this._valueCache[uniformName];
  772. if (cache !== undefined && cache === bool)
  773. return this;
  774. this._valueCache[uniformName] = bool;
  775. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  776. return this;
  777. };
  778. Effect.prototype.setVector2 = function (uniformName, vector2) {
  779. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  780. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  781. }
  782. return this;
  783. };
  784. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  785. if (this._cacheFloat2(uniformName, x, y)) {
  786. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  787. }
  788. return this;
  789. };
  790. Effect.prototype.setVector3 = function (uniformName, vector3) {
  791. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  792. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  793. }
  794. return this;
  795. };
  796. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  797. if (this._cacheFloat3(uniformName, x, y, z)) {
  798. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  799. }
  800. return this;
  801. };
  802. Effect.prototype.setVector4 = function (uniformName, vector4) {
  803. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  804. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  805. }
  806. return this;
  807. };
  808. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  809. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  810. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  811. }
  812. return this;
  813. };
  814. Effect.prototype.setColor3 = function (uniformName, color3) {
  815. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  816. this._engine.setColor3(this.getUniform(uniformName), color3);
  817. }
  818. return this;
  819. };
  820. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  821. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  822. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  823. }
  824. return this;
  825. };
  826. Effect.ResetCache = function () {
  827. Effect._baseCache = {};
  828. };
  829. Effect._uniqueIdSeed = 0;
  830. Effect._baseCache = {};
  831. // Statics
  832. Effect.ShadersStore = {};
  833. Effect.IncludesShadersStore = {};
  834. return Effect;
  835. }());
  836. BABYLON.Effect = Effect;
  837. })(BABYLON || (BABYLON = {}));
  838. //# sourceMappingURL=babylon.effect.js.map
  839. //# sourceMappingURL=babylon.types.js.map
  840. var BABYLON;
  841. (function (BABYLON) {
  842. var KeyboardEventTypes = /** @class */ (function () {
  843. function KeyboardEventTypes() {
  844. }
  845. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  846. get: function () {
  847. return KeyboardEventTypes._KEYDOWN;
  848. },
  849. enumerable: true,
  850. configurable: true
  851. });
  852. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  853. get: function () {
  854. return KeyboardEventTypes._KEYUP;
  855. },
  856. enumerable: true,
  857. configurable: true
  858. });
  859. KeyboardEventTypes._KEYDOWN = 0x01;
  860. KeyboardEventTypes._KEYUP = 0x02;
  861. return KeyboardEventTypes;
  862. }());
  863. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  864. var KeyboardInfo = /** @class */ (function () {
  865. function KeyboardInfo(type, event) {
  866. this.type = type;
  867. this.event = event;
  868. }
  869. return KeyboardInfo;
  870. }());
  871. BABYLON.KeyboardInfo = KeyboardInfo;
  872. /**
  873. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  874. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  875. */
  876. var KeyboardInfoPre = /** @class */ (function (_super) {
  877. __extends(KeyboardInfoPre, _super);
  878. function KeyboardInfoPre(type, event) {
  879. var _this = _super.call(this, type, event) || this;
  880. _this.skipOnPointerObservable = false;
  881. return _this;
  882. }
  883. return KeyboardInfoPre;
  884. }(KeyboardInfo));
  885. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  886. })(BABYLON || (BABYLON = {}));
  887. //# sourceMappingURL=babylon.keyboardEvents.js.map
  888. var BABYLON;
  889. (function (BABYLON) {
  890. var PointerEventTypes = /** @class */ (function () {
  891. function PointerEventTypes() {
  892. }
  893. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  894. get: function () {
  895. return PointerEventTypes._POINTERDOWN;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  901. get: function () {
  902. return PointerEventTypes._POINTERUP;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  908. get: function () {
  909. return PointerEventTypes._POINTERMOVE;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  915. get: function () {
  916. return PointerEventTypes._POINTERWHEEL;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  922. get: function () {
  923. return PointerEventTypes._POINTERPICK;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  929. get: function () {
  930. return PointerEventTypes._POINTERTAP;
  931. },
  932. enumerable: true,
  933. configurable: true
  934. });
  935. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  936. get: function () {
  937. return PointerEventTypes._POINTERDOUBLETAP;
  938. },
  939. enumerable: true,
  940. configurable: true
  941. });
  942. PointerEventTypes._POINTERDOWN = 0x01;
  943. PointerEventTypes._POINTERUP = 0x02;
  944. PointerEventTypes._POINTERMOVE = 0x04;
  945. PointerEventTypes._POINTERWHEEL = 0x08;
  946. PointerEventTypes._POINTERPICK = 0x10;
  947. PointerEventTypes._POINTERTAP = 0x20;
  948. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  949. return PointerEventTypes;
  950. }());
  951. BABYLON.PointerEventTypes = PointerEventTypes;
  952. var PointerInfoBase = /** @class */ (function () {
  953. function PointerInfoBase(type, event) {
  954. this.type = type;
  955. this.event = event;
  956. }
  957. return PointerInfoBase;
  958. }());
  959. BABYLON.PointerInfoBase = PointerInfoBase;
  960. /**
  961. * This class is used to store pointer related info for the onPrePointerObservable event.
  962. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  963. */
  964. var PointerInfoPre = /** @class */ (function (_super) {
  965. __extends(PointerInfoPre, _super);
  966. function PointerInfoPre(type, event, localX, localY) {
  967. var _this = _super.call(this, type, event) || this;
  968. _this.skipOnPointerObservable = false;
  969. _this.localPosition = new BABYLON.Vector2(localX, localY);
  970. return _this;
  971. }
  972. return PointerInfoPre;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfoPre = PointerInfoPre;
  975. /**
  976. * This type contains all the data related to a pointer event in Babylon.js.
  977. * 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.
  978. */
  979. var PointerInfo = /** @class */ (function (_super) {
  980. __extends(PointerInfo, _super);
  981. function PointerInfo(type, event, pickInfo) {
  982. var _this = _super.call(this, type, event) || this;
  983. _this.pickInfo = pickInfo;
  984. return _this;
  985. }
  986. return PointerInfo;
  987. }(PointerInfoBase));
  988. BABYLON.PointerInfo = PointerInfo;
  989. })(BABYLON || (BABYLON = {}));
  990. //# sourceMappingURL=babylon.pointerEvents.js.map
  991. var BABYLON;
  992. (function (BABYLON) {
  993. BABYLON.ToGammaSpace = 1 / 2.2;
  994. BABYLON.ToLinearSpace = 2.2;
  995. BABYLON.Epsilon = 0.001;
  996. /**
  997. * Class used to hold a RBG color
  998. */
  999. var Color3 = /** @class */ (function () {
  1000. /**
  1001. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1002. * @param r defines the red component (between 0 and 1, default is 0)
  1003. * @param g defines the green component (between 0 and 1, default is 0)
  1004. * @param b defines the blue component (between 0 and 1, default is 0)
  1005. */
  1006. function Color3(
  1007. /**
  1008. * Defines the red component (between 0 and 1, default is 0)
  1009. */
  1010. r,
  1011. /**
  1012. * Defines the green component (between 0 and 1, default is 0)
  1013. */
  1014. g,
  1015. /**
  1016. * Defines the blue component (between 0 and 1, default is 0)
  1017. */
  1018. b) {
  1019. if (r === void 0) { r = 0; }
  1020. if (g === void 0) { g = 0; }
  1021. if (b === void 0) { b = 0; }
  1022. this.r = r;
  1023. this.g = g;
  1024. this.b = b;
  1025. }
  1026. /**
  1027. * Creates a string with the Color3 current values
  1028. * @returns the string representation of the Color3 object
  1029. */
  1030. Color3.prototype.toString = function () {
  1031. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1032. };
  1033. /**
  1034. * Returns the string "Color3"
  1035. * @returns "Color3"
  1036. */
  1037. Color3.prototype.getClassName = function () {
  1038. return "Color3";
  1039. };
  1040. /**
  1041. * Compute the Color3 hash code
  1042. * @returns an unique number that can be used to hash Color3 objects
  1043. */
  1044. Color3.prototype.getHashCode = function () {
  1045. var hash = this.r || 0;
  1046. hash = (hash * 397) ^ (this.g || 0);
  1047. hash = (hash * 397) ^ (this.b || 0);
  1048. return hash;
  1049. };
  1050. // Operators
  1051. /**
  1052. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1053. * @param array defines the array where to store the r,g,b components
  1054. * @param index defines an optional index in the target array to define where to start storing values
  1055. * @returns the current Color3 object
  1056. */
  1057. Color3.prototype.toArray = function (array, index) {
  1058. if (index === undefined) {
  1059. index = 0;
  1060. }
  1061. array[index] = this.r;
  1062. array[index + 1] = this.g;
  1063. array[index + 2] = this.b;
  1064. return this;
  1065. };
  1066. /**
  1067. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1068. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1069. * @returns a new {BABYLON.Color4} object
  1070. */
  1071. Color3.prototype.toColor4 = function (alpha) {
  1072. if (alpha === void 0) { alpha = 1; }
  1073. return new Color4(this.r, this.g, this.b, alpha);
  1074. };
  1075. /**
  1076. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1077. * @returns the new array
  1078. */
  1079. Color3.prototype.asArray = function () {
  1080. var result = new Array();
  1081. this.toArray(result, 0);
  1082. return result;
  1083. };
  1084. /**
  1085. * Returns the luminance value
  1086. * @returns a float value
  1087. */
  1088. Color3.prototype.toLuminance = function () {
  1089. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1090. };
  1091. /**
  1092. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1093. * @param otherColor defines the second operand
  1094. * @returns the new Color3 object
  1095. */
  1096. Color3.prototype.multiply = function (otherColor) {
  1097. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1098. };
  1099. /**
  1100. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1101. * @param otherColor defines the second operand
  1102. * @param result defines the Color3 object where to store the result
  1103. * @returns the current Color3
  1104. */
  1105. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1106. result.r = this.r * otherColor.r;
  1107. result.g = this.g * otherColor.g;
  1108. result.b = this.b * otherColor.b;
  1109. return this;
  1110. };
  1111. /**
  1112. * Determines equality between Color3 objects
  1113. * @param otherColor defines the second operand
  1114. * @returns true if the rgb values are equal to the passed ones
  1115. */
  1116. Color3.prototype.equals = function (otherColor) {
  1117. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1118. };
  1119. /**
  1120. * Determines equality between the current Color3 object and a set of r,b,g values
  1121. * @param r defines the red component to check
  1122. * @param g defines the green component to check
  1123. * @param b defines the blue component to check
  1124. * @returns true if the rgb values are equal to the passed ones
  1125. */
  1126. Color3.prototype.equalsFloats = function (r, g, b) {
  1127. return this.r === r && this.g === g && this.b === b;
  1128. };
  1129. /**
  1130. * Multiplies in place each rgb value by scale
  1131. * @param scale defines the scaling factor
  1132. * @returns the updated Color3.
  1133. */
  1134. Color3.prototype.scale = function (scale) {
  1135. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1136. };
  1137. /**
  1138. * Multiplies the rgb values by scale and stores the result into "result"
  1139. * @param scale defines the scaling factor
  1140. * @param result defines the Color3 object where to store the result
  1141. * @returns the unmodified current Color3.
  1142. */
  1143. Color3.prototype.scaleToRef = function (scale, result) {
  1144. result.r = this.r * scale;
  1145. result.g = this.g * scale;
  1146. result.b = this.b * scale;
  1147. return this;
  1148. };
  1149. /**
  1150. * Clamps the rgb values by the min and max values and stores the result into "result"
  1151. * @param min defines minimum clamping value (default is 0)
  1152. * @param max defines maximum clamping value (default is 1)
  1153. * @param result defines color to store the result into
  1154. * @returns the original Color3
  1155. */
  1156. Color3.prototype.clampToRef = function (min, max, result) {
  1157. if (min === void 0) { min = 0; }
  1158. if (max === void 0) { max = 1; }
  1159. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1160. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1161. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1162. return this;
  1163. };
  1164. /**
  1165. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1166. * @param otherColor defines the second operand
  1167. * @returns the new Color3
  1168. */
  1169. Color3.prototype.add = function (otherColor) {
  1170. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1171. };
  1172. /**
  1173. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1174. * @param otherColor defines the second operand
  1175. * @param result defines Color3 object to store the result into
  1176. * @returns the unmodified current Color3
  1177. */
  1178. Color3.prototype.addToRef = function (otherColor, result) {
  1179. result.r = this.r + otherColor.r;
  1180. result.g = this.g + otherColor.g;
  1181. result.b = this.b + otherColor.b;
  1182. return this;
  1183. };
  1184. /**
  1185. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1186. * @param otherColor defines the second operand
  1187. * @returns the new Color3
  1188. */
  1189. Color3.prototype.subtract = function (otherColor) {
  1190. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1191. };
  1192. /**
  1193. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1194. * @param otherColor defines the second operand
  1195. * @param result defines Color3 object to store the result into
  1196. * @returns the unmodified current Color3
  1197. */
  1198. Color3.prototype.subtractToRef = function (otherColor, result) {
  1199. result.r = this.r - otherColor.r;
  1200. result.g = this.g - otherColor.g;
  1201. result.b = this.b - otherColor.b;
  1202. return this;
  1203. };
  1204. /**
  1205. * Copy the current object
  1206. * @returns a new Color3 copied the current one
  1207. */
  1208. Color3.prototype.clone = function () {
  1209. return new Color3(this.r, this.g, this.b);
  1210. };
  1211. /**
  1212. * Copies the rgb values from the source in the current Color3
  1213. * @param source defines the source Color3 object
  1214. * @returns the updated Color3 object
  1215. */
  1216. Color3.prototype.copyFrom = function (source) {
  1217. this.r = source.r;
  1218. this.g = source.g;
  1219. this.b = source.b;
  1220. return this;
  1221. };
  1222. /**
  1223. * Updates the Color3 rgb values from the passed floats
  1224. * @param r defines the red component to read from
  1225. * @param g defines the green component to read from
  1226. * @param b defines the blue component to read from
  1227. * @returns the current Color3 object
  1228. */
  1229. Color3.prototype.copyFromFloats = function (r, g, b) {
  1230. this.r = r;
  1231. this.g = g;
  1232. this.b = b;
  1233. return this;
  1234. };
  1235. /**
  1236. * Updates the Color3 rgb values from the passed floats
  1237. * @param r defines the red component to read from
  1238. * @param g defines the green component to read from
  1239. * @param b defines the blue component to read from
  1240. * @returns the current Color3 object
  1241. */
  1242. Color3.prototype.set = function (r, g, b) {
  1243. return this.copyFromFloats(r, g, b);
  1244. };
  1245. /**
  1246. * Compute the Color3 hexadecimal code as a string
  1247. * @returns a string containing the hexadecimal representation of the Color3 object
  1248. */
  1249. Color3.prototype.toHexString = function () {
  1250. var intR = (this.r * 255) | 0;
  1251. var intG = (this.g * 255) | 0;
  1252. var intB = (this.b * 255) | 0;
  1253. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1254. };
  1255. /**
  1256. * Computes a new Color3 converted from the current one to linear space
  1257. * @returns a new Color3 object
  1258. */
  1259. Color3.prototype.toLinearSpace = function () {
  1260. var convertedColor = new Color3();
  1261. this.toLinearSpaceToRef(convertedColor);
  1262. return convertedColor;
  1263. };
  1264. /**
  1265. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1266. * @param convertedColor defines the Color3 object where to store the linear space version
  1267. * @returns the unmodified Color3
  1268. */
  1269. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1270. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1271. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1272. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1273. return this;
  1274. };
  1275. /**
  1276. * Computes a new Color3 converted from the current one to gamma space
  1277. * @returns a new Color3 object
  1278. */
  1279. Color3.prototype.toGammaSpace = function () {
  1280. var convertedColor = new Color3();
  1281. this.toGammaSpaceToRef(convertedColor);
  1282. return convertedColor;
  1283. };
  1284. /**
  1285. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1286. * @param convertedColor defines the Color3 object where to store the gamma space version
  1287. * @returns the unmodified Color3
  1288. */
  1289. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1290. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1291. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1292. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1293. return this;
  1294. };
  1295. // Statics
  1296. /**
  1297. * Creates a new Color3 from the string containing valid hexadecimal values
  1298. * @param hex defines a string containing valid hexadecimal values
  1299. * @returns a new Color3 object
  1300. */
  1301. Color3.FromHexString = function (hex) {
  1302. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1303. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1304. return new Color3(0, 0, 0);
  1305. }
  1306. var r = parseInt(hex.substring(1, 3), 16);
  1307. var g = parseInt(hex.substring(3, 5), 16);
  1308. var b = parseInt(hex.substring(5, 7), 16);
  1309. return Color3.FromInts(r, g, b);
  1310. };
  1311. /**
  1312. * Creates a new Vector3 from the starting index of the passed array
  1313. * @param array defines the source array
  1314. * @param offset defines an offset in the source array
  1315. * @returns a new Color3 object
  1316. */
  1317. Color3.FromArray = function (array, offset) {
  1318. if (offset === void 0) { offset = 0; }
  1319. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Creates a new Color3 from integer values (< 256)
  1323. * @param r defines the red component to read from (value between 0 and 255)
  1324. * @param g defines the green component to read from (value between 0 and 255)
  1325. * @param b defines the blue component to read from (value between 0 and 255)
  1326. * @returns a new Color3 object
  1327. */
  1328. Color3.FromInts = function (r, g, b) {
  1329. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1330. };
  1331. /**
  1332. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1333. * @param start defines the start Color3 value
  1334. * @param end defines the end Color3 value
  1335. * @param amount defines the gradient value between start and end
  1336. * @returns a new Color3 object
  1337. */
  1338. Color3.Lerp = function (start, end, amount) {
  1339. var r = start.r + ((end.r - start.r) * amount);
  1340. var g = start.g + ((end.g - start.g) * amount);
  1341. var b = start.b + ((end.b - start.b) * amount);
  1342. return new Color3(r, g, b);
  1343. };
  1344. /**
  1345. * Returns a Color3 value containing a red color
  1346. * @returns a new Color3 object
  1347. */
  1348. Color3.Red = function () { return new Color3(1, 0, 0); };
  1349. /**
  1350. * Returns a Color3 value containing a green color
  1351. * @returns a new Color3 object
  1352. */
  1353. Color3.Green = function () { return new Color3(0, 1, 0); };
  1354. /**
  1355. * Returns a Color3 value containing a blue color
  1356. * @returns a new Color3 object
  1357. */
  1358. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1359. /**
  1360. * Returns a Color3 value containing a black color
  1361. * @returns a new Color3 object
  1362. */
  1363. Color3.Black = function () { return new Color3(0, 0, 0); };
  1364. /**
  1365. * Returns a Color3 value containing a white color
  1366. * @returns a new Color3 object
  1367. */
  1368. Color3.White = function () { return new Color3(1, 1, 1); };
  1369. /**
  1370. * Returns a Color3 value containing a purple color
  1371. * @returns a new Color3 object
  1372. */
  1373. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1374. /**
  1375. * Returns a Color3 value containing a magenta color
  1376. * @returns a new Color3 object
  1377. */
  1378. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1379. /**
  1380. * Returns a Color3 value containing a yellow color
  1381. * @returns a new Color3 object
  1382. */
  1383. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1384. /**
  1385. * Returns a Color3 value containing a gray color
  1386. * @returns a new Color3 object
  1387. */
  1388. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1389. /**
  1390. * Returns a Color3 value containing a teal color
  1391. * @returns a new Color3 object
  1392. */
  1393. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1394. /**
  1395. * Returns a Color3 value containing a random color
  1396. * @returns a new Color3 object
  1397. */
  1398. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1399. return Color3;
  1400. }());
  1401. BABYLON.Color3 = Color3;
  1402. /**
  1403. * Class used to hold a RBGA color
  1404. */
  1405. var Color4 = /** @class */ (function () {
  1406. /**
  1407. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1408. * @param r defines the red component (between 0 and 1, default is 0)
  1409. * @param g defines the green component (between 0 and 1, default is 0)
  1410. * @param b defines the blue component (between 0 and 1, default is 0)
  1411. * @param a defines the alpha component (between 0 and 1, default is 1)
  1412. */
  1413. function Color4(
  1414. /**
  1415. * Defines the red component (between 0 and 1, default is 0)
  1416. */
  1417. r,
  1418. /**
  1419. * Defines the green component (between 0 and 1, default is 0)
  1420. */
  1421. g,
  1422. /**
  1423. * Defines the blue component (between 0 and 1, default is 0)
  1424. */
  1425. b,
  1426. /**
  1427. * Defines the alpha component (between 0 and 1, default is 1)
  1428. */
  1429. a) {
  1430. if (r === void 0) { r = 0; }
  1431. if (g === void 0) { g = 0; }
  1432. if (b === void 0) { b = 0; }
  1433. if (a === void 0) { a = 1; }
  1434. this.r = r;
  1435. this.g = g;
  1436. this.b = b;
  1437. this.a = a;
  1438. }
  1439. // Operators
  1440. /**
  1441. * Adds in place the passed Color4 values to the current Color4 object
  1442. * @param right defines the second operand
  1443. * @returns the current updated Color4 object
  1444. */
  1445. Color4.prototype.addInPlace = function (right) {
  1446. this.r += right.r;
  1447. this.g += right.g;
  1448. this.b += right.b;
  1449. this.a += right.a;
  1450. return this;
  1451. };
  1452. /**
  1453. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1454. * @returns the new array
  1455. */
  1456. Color4.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Stores from the starting index in the passed array the Color4 successive values
  1463. * @param array defines the array where to store the r,g,b components
  1464. * @param index defines an optional index in the target array to define where to start storing values
  1465. * @returns the current Color4 object
  1466. */
  1467. Color4.prototype.toArray = function (array, index) {
  1468. if (index === undefined) {
  1469. index = 0;
  1470. }
  1471. array[index] = this.r;
  1472. array[index + 1] = this.g;
  1473. array[index + 2] = this.b;
  1474. array[index + 3] = this.a;
  1475. return this;
  1476. };
  1477. /**
  1478. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1479. * @param right defines the second operand
  1480. * @returns a new Color4 object
  1481. */
  1482. Color4.prototype.add = function (right) {
  1483. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1484. };
  1485. /**
  1486. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1487. * @param right defines the second operand
  1488. * @returns a new Color4 object
  1489. */
  1490. Color4.prototype.subtract = function (right) {
  1491. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1492. };
  1493. /**
  1494. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1495. * @param right defines the second operand
  1496. * @param result defines the Color4 object where to store the result
  1497. * @returns the current Color4 object
  1498. */
  1499. Color4.prototype.subtractToRef = function (right, result) {
  1500. result.r = this.r - right.r;
  1501. result.g = this.g - right.g;
  1502. result.b = this.b - right.b;
  1503. result.a = this.a - right.a;
  1504. return this;
  1505. };
  1506. /**
  1507. * Creates a new Color4 with the current Color4 values multiplied by scale
  1508. * @param scale defines the scaling factor to apply
  1509. * @returns a new Color4 object
  1510. */
  1511. Color4.prototype.scale = function (scale) {
  1512. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1513. };
  1514. /**
  1515. * Multiplies the current Color4 values by scale and stores the result in "result"
  1516. * @param scale defines the scaling factor to apply
  1517. * @param result defines the Color4 object where to store the result
  1518. * @returns the current Color4.
  1519. */
  1520. Color4.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. result.a = this.a * scale;
  1525. return this;
  1526. };
  1527. /**
  1528. * Clamps the rgb values by the min and max values and stores the result into "result"
  1529. * @param min defines minimum clamping value (default is 0)
  1530. * @param max defines maximum clamping value (default is 1)
  1531. * @param result defines color to store the result into.
  1532. * @returns the cuurent Color4
  1533. */
  1534. Color4.prototype.clampToRef = function (min, max, result) {
  1535. if (min === void 0) { min = 0; }
  1536. if (max === void 0) { max = 1; }
  1537. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1538. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1539. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1540. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1541. return this;
  1542. };
  1543. /**
  1544. * Multipy an Color4 value by another and return a new Color4 object
  1545. * @param color defines the Color4 value to multiply by
  1546. * @returns a new Color4 object
  1547. */
  1548. Color4.prototype.multiply = function (color) {
  1549. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1550. };
  1551. /**
  1552. * Multipy a Color4 value by another and push the result in a reference value
  1553. * @param color defines the Color4 value to multiply by
  1554. * @param result defines the Color4 to fill the result in
  1555. * @returns the result Color4
  1556. */
  1557. Color4.prototype.multiplyToRef = function (color, result) {
  1558. result.r = this.r * color.r;
  1559. result.g = this.g * color.g;
  1560. result.b = this.b * color.b;
  1561. result.a = this.a * color.a;
  1562. return result;
  1563. };
  1564. /**
  1565. * Creates a string with the Color4 current values
  1566. * @returns the string representation of the Color4 object
  1567. */
  1568. Color4.prototype.toString = function () {
  1569. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1570. };
  1571. /**
  1572. * Returns the string "Color4"
  1573. * @returns "Color4"
  1574. */
  1575. Color4.prototype.getClassName = function () {
  1576. return "Color4";
  1577. };
  1578. /**
  1579. * Compute the Color4 hash code
  1580. * @returns an unique number that can be used to hash Color4 objects
  1581. */
  1582. Color4.prototype.getHashCode = function () {
  1583. var hash = this.r || 0;
  1584. hash = (hash * 397) ^ (this.g || 0);
  1585. hash = (hash * 397) ^ (this.b || 0);
  1586. hash = (hash * 397) ^ (this.a || 0);
  1587. return hash;
  1588. };
  1589. /**
  1590. * Creates a new Color4 copied from the current one
  1591. * @returns a new Color4 object
  1592. */
  1593. Color4.prototype.clone = function () {
  1594. return new Color4(this.r, this.g, this.b, this.a);
  1595. };
  1596. /**
  1597. * Copies the passed Color4 values into the current one
  1598. * @param source defines the source Color4 object
  1599. * @returns the current updated Color4 object
  1600. */
  1601. Color4.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. this.a = source.a;
  1606. return this;
  1607. };
  1608. /**
  1609. * Copies the passed float values into the current one
  1610. * @param r defines the red component to read from
  1611. * @param g defines the green component to read from
  1612. * @param b defines the blue component to read from
  1613. * @param a defines the alpha component to read from
  1614. * @returns the current updated Color4 object
  1615. */
  1616. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. this.a = a;
  1621. return this;
  1622. };
  1623. /**
  1624. * Copies the passed float values into the current one
  1625. * @param r defines the red component to read from
  1626. * @param g defines the green component to read from
  1627. * @param b defines the blue component to read from
  1628. * @param a defines the alpha component to read from
  1629. * @returns the current updated Color4 object
  1630. */
  1631. Color4.prototype.set = function (r, g, b, a) {
  1632. return this.copyFromFloats(r, g, b, a);
  1633. };
  1634. /**
  1635. * Compute the Color4 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color4 object
  1637. */
  1638. Color4.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. var intA = (this.a * 255) | 0;
  1643. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1644. };
  1645. /**
  1646. * Computes a new Color4 converted from the current one to linear space
  1647. * @returns a new Color4 object
  1648. */
  1649. Color4.prototype.toLinearSpace = function () {
  1650. var convertedColor = new Color4();
  1651. this.toLinearSpaceToRef(convertedColor);
  1652. return convertedColor;
  1653. };
  1654. /**
  1655. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1656. * @param convertedColor defines the Color4 object where to store the linear space version
  1657. * @returns the unmodified Color4
  1658. */
  1659. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1660. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1661. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1662. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1663. convertedColor.a = this.a;
  1664. return this;
  1665. };
  1666. /**
  1667. * Computes a new Color4 converted from the current one to gamma space
  1668. * @returns a new Color4 object
  1669. */
  1670. Color4.prototype.toGammaSpace = function () {
  1671. var convertedColor = new Color4();
  1672. this.toGammaSpaceToRef(convertedColor);
  1673. return convertedColor;
  1674. };
  1675. /**
  1676. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1677. * @param convertedColor defines the Color4 object where to store the gamma space version
  1678. * @returns the unmodified Color4
  1679. */
  1680. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1681. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1682. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1683. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1684. convertedColor.a = this.a;
  1685. return this;
  1686. };
  1687. // Statics
  1688. /**
  1689. * Creates a new Color4 from the string containing valid hexadecimal values
  1690. * @param hex defines a string containing valid hexadecimal values
  1691. * @returns a new Color4 object
  1692. */
  1693. Color4.FromHexString = function (hex) {
  1694. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1695. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1696. return new Color4(0.0, 0.0, 0.0, 0.0);
  1697. }
  1698. var r = parseInt(hex.substring(1, 3), 16);
  1699. var g = parseInt(hex.substring(3, 5), 16);
  1700. var b = parseInt(hex.substring(5, 7), 16);
  1701. var a = parseInt(hex.substring(7, 9), 16);
  1702. return Color4.FromInts(r, g, b, a);
  1703. };
  1704. /**
  1705. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1706. * @param left defines the start value
  1707. * @param right defines the end value
  1708. * @param amount defines the gradient factor
  1709. * @returns a new Color4 object
  1710. */
  1711. Color4.Lerp = function (left, right, amount) {
  1712. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1713. Color4.LerpToRef(left, right, amount, result);
  1714. return result;
  1715. };
  1716. /**
  1717. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1718. * @param left defines the start value
  1719. * @param right defines the end value
  1720. * @param amount defines the gradient factor
  1721. * @param result defines the Color4 object where to store data
  1722. */
  1723. Color4.LerpToRef = function (left, right, amount, result) {
  1724. result.r = left.r + (right.r - left.r) * amount;
  1725. result.g = left.g + (right.g - left.g) * amount;
  1726. result.b = left.b + (right.b - left.b) * amount;
  1727. result.a = left.a + (right.a - left.a) * amount;
  1728. };
  1729. /**
  1730. * Creates a new Color4 from the starting index element of the passed array
  1731. * @param array defines the source array to read from
  1732. * @param offset defines the offset in the source array
  1733. * @returns a new Color4 object
  1734. */
  1735. Color4.FromArray = function (array, offset) {
  1736. if (offset === void 0) { offset = 0; }
  1737. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1738. };
  1739. /**
  1740. * Creates a new Color3 from integer values (< 256)
  1741. * @param r defines the red component to read from (value between 0 and 255)
  1742. * @param g defines the green component to read from (value between 0 and 255)
  1743. * @param b defines the blue component to read from (value between 0 and 255)
  1744. * @param a defines the alpha component to read from (value between 0 and 255)
  1745. * @returns a new Color3 object
  1746. */
  1747. Color4.FromInts = function (r, g, b, a) {
  1748. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1749. };
  1750. /**
  1751. * Check the content of a given array and convert it to an array containing RGBA data
  1752. * If the original array was already containing count * 4 values then it is returned directly
  1753. * @param colors defines the array to check
  1754. * @param count defines the number of RGBA data to expect
  1755. * @returns an array containing count * 4 values (RGBA)
  1756. */
  1757. Color4.CheckColors4 = function (colors, count) {
  1758. // Check if color3 was used
  1759. if (colors.length === count * 3) {
  1760. var colors4 = [];
  1761. for (var index = 0; index < colors.length; index += 3) {
  1762. var newIndex = (index / 3) * 4;
  1763. colors4[newIndex] = colors[index];
  1764. colors4[newIndex + 1] = colors[index + 1];
  1765. colors4[newIndex + 2] = colors[index + 2];
  1766. colors4[newIndex + 3] = 1.0;
  1767. }
  1768. return colors4;
  1769. }
  1770. return colors;
  1771. };
  1772. return Color4;
  1773. }());
  1774. BABYLON.Color4 = Color4;
  1775. var Vector2 = /** @class */ (function () {
  1776. /**
  1777. * Creates a new Vector2 from the passed x and y coordinates.
  1778. */
  1779. function Vector2(x, y) {
  1780. this.x = x;
  1781. this.y = y;
  1782. }
  1783. /**
  1784. * Returns a string with the Vector2 coordinates.
  1785. */
  1786. Vector2.prototype.toString = function () {
  1787. return "{X: " + this.x + " Y:" + this.y + "}";
  1788. };
  1789. /**
  1790. * Returns the string "Vector2"
  1791. */
  1792. Vector2.prototype.getClassName = function () {
  1793. return "Vector2";
  1794. };
  1795. /**
  1796. * Returns the Vector2 hash code as a number.
  1797. */
  1798. Vector2.prototype.getHashCode = function () {
  1799. var hash = this.x || 0;
  1800. hash = (hash * 397) ^ (this.y || 0);
  1801. return hash;
  1802. };
  1803. // Operators
  1804. /**
  1805. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1806. * Returns the Vector2.
  1807. */
  1808. Vector2.prototype.toArray = function (array, index) {
  1809. if (index === void 0) { index = 0; }
  1810. array[index] = this.x;
  1811. array[index + 1] = this.y;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new array with 2 elements : the Vector2 coordinates.
  1816. */
  1817. Vector2.prototype.asArray = function () {
  1818. var result = new Array();
  1819. this.toArray(result, 0);
  1820. return result;
  1821. };
  1822. /**
  1823. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1824. * Returns the updated Vector2.
  1825. */
  1826. Vector2.prototype.copyFrom = function (source) {
  1827. this.x = source.x;
  1828. this.y = source.y;
  1829. return this;
  1830. };
  1831. /**
  1832. * Sets the Vector2 coordinates with the passed floats.
  1833. * Returns the updated Vector2.
  1834. */
  1835. Vector2.prototype.copyFromFloats = function (x, y) {
  1836. this.x = x;
  1837. this.y = y;
  1838. return this;
  1839. };
  1840. /**
  1841. * Sets the Vector2 coordinates with the passed floats.
  1842. * Returns the updated Vector2.
  1843. */
  1844. Vector2.prototype.set = function (x, y) {
  1845. return this.copyFromFloats(x, y);
  1846. };
  1847. /**
  1848. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1849. */
  1850. Vector2.prototype.add = function (otherVector) {
  1851. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1852. };
  1853. /**
  1854. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1855. * Returns the Vector2.
  1856. */
  1857. Vector2.prototype.addToRef = function (otherVector, result) {
  1858. result.x = this.x + otherVector.x;
  1859. result.y = this.y + otherVector.y;
  1860. return this;
  1861. };
  1862. /**
  1863. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1864. * Returns the updated Vector2.
  1865. */
  1866. Vector2.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. return this;
  1870. };
  1871. /**
  1872. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1873. */
  1874. Vector2.prototype.addVector3 = function (otherVector) {
  1875. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1876. };
  1877. /**
  1878. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1879. */
  1880. Vector2.prototype.subtract = function (otherVector) {
  1881. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1882. };
  1883. /**
  1884. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1885. * Returns the Vector2.
  1886. */
  1887. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1888. result.x = this.x - otherVector.x;
  1889. result.y = this.y - otherVector.y;
  1890. return this;
  1891. };
  1892. /**
  1893. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1894. * Returns the updated Vector2.
  1895. */
  1896. Vector2.prototype.subtractInPlace = function (otherVector) {
  1897. this.x -= otherVector.x;
  1898. this.y -= otherVector.y;
  1899. return this;
  1900. };
  1901. /**
  1902. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1903. * Returns the updated Vector2.
  1904. */
  1905. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1906. this.x *= otherVector.x;
  1907. this.y *= otherVector.y;
  1908. return this;
  1909. };
  1910. /**
  1911. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1912. */
  1913. Vector2.prototype.multiply = function (otherVector) {
  1914. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1915. };
  1916. /**
  1917. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1918. * Returns the Vector2.
  1919. */
  1920. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1921. result.x = this.x * otherVector.x;
  1922. result.y = this.y * otherVector.y;
  1923. return this;
  1924. };
  1925. /**
  1926. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1927. */
  1928. Vector2.prototype.multiplyByFloats = function (x, y) {
  1929. return new Vector2(this.x * x, this.y * y);
  1930. };
  1931. /**
  1932. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1933. */
  1934. Vector2.prototype.divide = function (otherVector) {
  1935. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1936. };
  1937. /**
  1938. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1939. * Returns the Vector2.
  1940. */
  1941. Vector2.prototype.divideToRef = function (otherVector, result) {
  1942. result.x = this.x / otherVector.x;
  1943. result.y = this.y / otherVector.y;
  1944. return this;
  1945. };
  1946. /**
  1947. * Divides the current Vector3 coordinates by the passed ones.
  1948. * Returns the updated Vector3.
  1949. */
  1950. Vector2.prototype.divideInPlace = function (otherVector) {
  1951. return this.divideToRef(otherVector, this);
  1952. };
  1953. /**
  1954. * Returns a new Vector2 with current Vector2 negated coordinates.
  1955. */
  1956. Vector2.prototype.negate = function () {
  1957. return new Vector2(-this.x, -this.y);
  1958. };
  1959. /**
  1960. * Multiply the Vector2 coordinates by scale.
  1961. * Returns the updated Vector2.
  1962. */
  1963. Vector2.prototype.scaleInPlace = function (scale) {
  1964. this.x *= scale;
  1965. this.y *= scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1970. */
  1971. Vector2.prototype.scale = function (scale) {
  1972. return new Vector2(this.x * scale, this.y * scale);
  1973. };
  1974. /**
  1975. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1976. */
  1977. Vector2.prototype.equals = function (otherVector) {
  1978. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1979. };
  1980. /**
  1981. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1982. */
  1983. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1984. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1985. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1986. };
  1987. // Properties
  1988. /**
  1989. * Returns the vector length (float).
  1990. */
  1991. Vector2.prototype.length = function () {
  1992. return Math.sqrt(this.x * this.x + this.y * this.y);
  1993. };
  1994. /**
  1995. * Returns the vector squared length (float);
  1996. */
  1997. Vector2.prototype.lengthSquared = function () {
  1998. return (this.x * this.x + this.y * this.y);
  1999. };
  2000. // Methods
  2001. /**
  2002. * Normalize the vector.
  2003. * Returns the updated Vector2.
  2004. */
  2005. Vector2.prototype.normalize = function () {
  2006. var len = this.length();
  2007. if (len === 0)
  2008. return this;
  2009. var num = 1.0 / len;
  2010. this.x *= num;
  2011. this.y *= num;
  2012. return this;
  2013. };
  2014. /**
  2015. * Returns a new Vector2 copied from the Vector2.
  2016. */
  2017. Vector2.prototype.clone = function () {
  2018. return new Vector2(this.x, this.y);
  2019. };
  2020. // Statics
  2021. /**
  2022. * Returns a new Vector2(0, 0)
  2023. */
  2024. Vector2.Zero = function () {
  2025. return new Vector2(0, 0);
  2026. };
  2027. /**
  2028. * Returns a new Vector2(1, 1)
  2029. */
  2030. Vector2.One = function () {
  2031. return new Vector2(1, 1);
  2032. };
  2033. /**
  2034. * Returns a new Vector2 set from the passed index element of the passed array.
  2035. */
  2036. Vector2.FromArray = function (array, offset) {
  2037. if (offset === void 0) { offset = 0; }
  2038. return new Vector2(array[offset], array[offset + 1]);
  2039. };
  2040. /**
  2041. * Sets "result" from the passed index element of the passed array.
  2042. */
  2043. Vector2.FromArrayToRef = function (array, offset, result) {
  2044. result.x = array[offset];
  2045. result.y = array[offset + 1];
  2046. };
  2047. /**
  2048. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2049. */
  2050. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2051. var squared = amount * amount;
  2052. var cubed = amount * squared;
  2053. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2054. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2055. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2056. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2057. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2058. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * 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".
  2063. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2064. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2065. */
  2066. Vector2.Clamp = function (value, min, max) {
  2067. var x = value.x;
  2068. x = (x > max.x) ? max.x : x;
  2069. x = (x < min.x) ? min.x : x;
  2070. var y = value.y;
  2071. y = (y > max.y) ? max.y : y;
  2072. y = (y < min.y) ? min.y : y;
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2077. */
  2078. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2079. var squared = amount * amount;
  2080. var cubed = amount * squared;
  2081. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2082. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2083. var part3 = (cubed - (2.0 * squared)) + amount;
  2084. var part4 = cubed - squared;
  2085. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2086. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2087. return new Vector2(x, y);
  2088. };
  2089. /**
  2090. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2091. */
  2092. Vector2.Lerp = function (start, end, amount) {
  2093. var x = start.x + ((end.x - start.x) * amount);
  2094. var y = start.y + ((end.y - start.y) * amount);
  2095. return new Vector2(x, y);
  2096. };
  2097. /**
  2098. * Returns the dot product (float) of the vector "left" and the vector "right".
  2099. */
  2100. Vector2.Dot = function (left, right) {
  2101. return left.x * right.x + left.y * right.y;
  2102. };
  2103. /**
  2104. * Returns a new Vector2 equal to the normalized passed vector.
  2105. */
  2106. Vector2.Normalize = function (vector) {
  2107. var newVector = vector.clone();
  2108. newVector.normalize();
  2109. return newVector;
  2110. };
  2111. /**
  2112. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2113. */
  2114. Vector2.Minimize = function (left, right) {
  2115. var x = (left.x < right.x) ? left.x : right.x;
  2116. var y = (left.y < right.y) ? left.y : right.y;
  2117. return new Vector2(x, y);
  2118. };
  2119. /**
  2120. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2121. */
  2122. Vector2.Maximize = function (left, right) {
  2123. var x = (left.x > right.x) ? left.x : right.x;
  2124. var y = (left.y > right.y) ? left.y : right.y;
  2125. return new Vector2(x, y);
  2126. };
  2127. /**
  2128. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2129. */
  2130. Vector2.Transform = function (vector, transformation) {
  2131. var r = Vector2.Zero();
  2132. Vector2.TransformToRef(vector, transformation, r);
  2133. return r;
  2134. };
  2135. /**
  2136. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2137. */
  2138. Vector2.TransformToRef = function (vector, transformation, result) {
  2139. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2140. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2141. result.x = x;
  2142. result.y = y;
  2143. };
  2144. /**
  2145. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2146. */
  2147. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2148. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2149. var sign = a < 0 ? -1 : 1;
  2150. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2151. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2152. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2153. };
  2154. /**
  2155. * Returns the distance (float) between the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Distance = function (value1, value2) {
  2158. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2159. };
  2160. /**
  2161. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2162. */
  2163. Vector2.DistanceSquared = function (value1, value2) {
  2164. var x = value1.x - value2.x;
  2165. var y = value1.y - value2.y;
  2166. return (x * x) + (y * y);
  2167. };
  2168. /**
  2169. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2170. */
  2171. Vector2.Center = function (value1, value2) {
  2172. var center = value1.add(value2);
  2173. center.scaleInPlace(0.5);
  2174. return center;
  2175. };
  2176. /**
  2177. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2178. */
  2179. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2180. var l2 = Vector2.DistanceSquared(segA, segB);
  2181. if (l2 === 0.0) {
  2182. return Vector2.Distance(p, segA);
  2183. }
  2184. var v = segB.subtract(segA);
  2185. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2186. var proj = segA.add(v.multiplyByFloats(t, t));
  2187. return Vector2.Distance(p, proj);
  2188. };
  2189. return Vector2;
  2190. }());
  2191. BABYLON.Vector2 = Vector2;
  2192. var Vector3 = /** @class */ (function () {
  2193. /**
  2194. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2195. * A Vector3 is the main object used in 3D geometry.
  2196. * It can represent etiher the coordinates of a point the space, either a direction.
  2197. */
  2198. function Vector3(x, y, z) {
  2199. this.x = x;
  2200. this.y = y;
  2201. this.z = z;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector3 coordinates.
  2205. */
  2206. Vector3.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector3"
  2211. */
  2212. Vector3.prototype.getClassName = function () {
  2213. return "Vector3";
  2214. };
  2215. /**
  2216. * Returns the Vector hash code.
  2217. */
  2218. Vector3.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. hash = (hash * 397) ^ (this.z || 0);
  2222. return hash;
  2223. };
  2224. // Operators
  2225. /**
  2226. * Returns a new array with three elements : the coordinates the Vector3.
  2227. */
  2228. Vector3.prototype.asArray = function () {
  2229. var result = [];
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2235. * Returns the Vector3.
  2236. */
  2237. Vector3.prototype.toArray = function (array, index) {
  2238. if (index === void 0) { index = 0; }
  2239. array[index] = this.x;
  2240. array[index + 1] = this.y;
  2241. array[index + 2] = this.z;
  2242. return this;
  2243. };
  2244. /**
  2245. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2246. */
  2247. Vector3.prototype.toQuaternion = function () {
  2248. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2249. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2250. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2251. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2252. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2253. var cosy = Math.cos(this.y * 0.5);
  2254. var siny = Math.sin(this.y * 0.5);
  2255. result.x = coszMinusx * siny;
  2256. result.y = -sinzMinusx * siny;
  2257. result.z = sinxPlusz * cosy;
  2258. result.w = cosxPlusz * cosy;
  2259. return result;
  2260. };
  2261. /**
  2262. * Adds the passed vector to the current Vector3.
  2263. * Returns the updated Vector3.
  2264. */
  2265. Vector3.prototype.addInPlace = function (otherVector) {
  2266. this.x += otherVector.x;
  2267. this.y += otherVector.y;
  2268. this.z += otherVector.z;
  2269. return this;
  2270. };
  2271. /**
  2272. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2273. */
  2274. Vector3.prototype.add = function (otherVector) {
  2275. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2276. };
  2277. /**
  2278. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2279. * Returns the current Vector3.
  2280. */
  2281. Vector3.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. result.z = this.z + otherVector.z;
  2285. return this;
  2286. };
  2287. /**
  2288. * Subtract the passed vector from the current Vector3.
  2289. * Returns the updated Vector3.
  2290. */
  2291. Vector3.prototype.subtractInPlace = function (otherVector) {
  2292. this.x -= otherVector.x;
  2293. this.y -= otherVector.y;
  2294. this.z -= otherVector.z;
  2295. return this;
  2296. };
  2297. /**
  2298. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2299. */
  2300. Vector3.prototype.subtract = function (otherVector) {
  2301. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2302. };
  2303. /**
  2304. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2305. * Returns the current Vector3.
  2306. */
  2307. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. result.z = this.z - otherVector.z;
  2311. return this;
  2312. };
  2313. /**
  2314. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2315. */
  2316. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2317. return new Vector3(this.x - x, this.y - y, this.z - z);
  2318. };
  2319. /**
  2320. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2321. * Returns the current Vector3.
  2322. */
  2323. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2324. result.x = this.x - x;
  2325. result.y = this.y - y;
  2326. result.z = this.z - z;
  2327. return this;
  2328. };
  2329. /**
  2330. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2331. */
  2332. Vector3.prototype.negate = function () {
  2333. return new Vector3(-this.x, -this.y, -this.z);
  2334. };
  2335. /**
  2336. * Multiplies the Vector3 coordinates by the float "scale".
  2337. * Returns the updated Vector3.
  2338. */
  2339. Vector3.prototype.scaleInPlace = function (scale) {
  2340. this.x *= scale;
  2341. this.y *= scale;
  2342. this.z *= scale;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2347. */
  2348. Vector3.prototype.scale = function (scale) {
  2349. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2350. };
  2351. /**
  2352. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2353. * Returns the current Vector3.
  2354. */
  2355. Vector3.prototype.scaleToRef = function (scale, result) {
  2356. result.x = this.x * scale;
  2357. result.y = this.y * scale;
  2358. result.z = this.z * scale;
  2359. return this;
  2360. };
  2361. /**
  2362. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2363. */
  2364. Vector3.prototype.equals = function (otherVector) {
  2365. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2366. };
  2367. /**
  2368. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2369. */
  2370. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2371. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2372. 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);
  2373. };
  2374. /**
  2375. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2376. */
  2377. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2378. return this.x === x && this.y === y && this.z === z;
  2379. };
  2380. /**
  2381. * Muliplies the current Vector3 coordinates by the passed ones.
  2382. * Returns the updated Vector3.
  2383. */
  2384. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2385. this.x *= otherVector.x;
  2386. this.y *= otherVector.y;
  2387. this.z *= otherVector.z;
  2388. return this;
  2389. };
  2390. /**
  2391. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2392. */
  2393. Vector3.prototype.multiply = function (otherVector) {
  2394. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2395. };
  2396. /**
  2397. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2398. * Returns the current Vector3.
  2399. */
  2400. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2401. result.x = this.x * otherVector.x;
  2402. result.y = this.y * otherVector.y;
  2403. result.z = this.z * otherVector.z;
  2404. return this;
  2405. };
  2406. /**
  2407. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2408. */
  2409. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2410. return new Vector3(this.x * x, this.y * y, this.z * z);
  2411. };
  2412. /**
  2413. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2414. */
  2415. Vector3.prototype.divide = function (otherVector) {
  2416. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2417. };
  2418. /**
  2419. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2420. * Returns the current Vector3.
  2421. */
  2422. Vector3.prototype.divideToRef = function (otherVector, result) {
  2423. result.x = this.x / otherVector.x;
  2424. result.y = this.y / otherVector.y;
  2425. result.z = this.z / otherVector.z;
  2426. return this;
  2427. };
  2428. /**
  2429. * Divides the current Vector3 coordinates by the passed ones.
  2430. * Returns the updated Vector3.
  2431. */
  2432. Vector3.prototype.divideInPlace = function (otherVector) {
  2433. return this.divideToRef(otherVector, this);
  2434. };
  2435. /**
  2436. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2437. * Returns the updated Vector3.
  2438. */
  2439. Vector3.prototype.MinimizeInPlace = function (other) {
  2440. if (other.x < this.x)
  2441. this.x = other.x;
  2442. if (other.y < this.y)
  2443. this.y = other.y;
  2444. if (other.z < this.z)
  2445. this.z = other.z;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2450. * Returns the updated Vector3.
  2451. */
  2452. Vector3.prototype.MaximizeInPlace = function (other) {
  2453. if (other.x > this.x)
  2454. this.x = other.x;
  2455. if (other.y > this.y)
  2456. this.y = other.y;
  2457. if (other.z > this.z)
  2458. this.z = other.z;
  2459. return this;
  2460. };
  2461. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2462. /**
  2463. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2464. */
  2465. get: function () {
  2466. var absX = Math.abs(this.x);
  2467. var absY = Math.abs(this.y);
  2468. if (absX !== absY) {
  2469. return true;
  2470. }
  2471. var absZ = Math.abs(this.z);
  2472. if (absX !== absZ) {
  2473. return true;
  2474. }
  2475. if (absY !== absZ) {
  2476. return true;
  2477. }
  2478. return false;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. // Properties
  2484. /**
  2485. * Returns the length of the Vector3 (float).
  2486. */
  2487. Vector3.prototype.length = function () {
  2488. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2489. };
  2490. /**
  2491. * Returns the squared length of the Vector3 (float).
  2492. */
  2493. Vector3.prototype.lengthSquared = function () {
  2494. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2495. };
  2496. /**
  2497. * Normalize the current Vector3.
  2498. * Returns the updated Vector3.
  2499. * /!\ In place operation.
  2500. */
  2501. Vector3.prototype.normalize = function () {
  2502. var len = this.length();
  2503. if (len === 0 || len === 1.0)
  2504. return this;
  2505. var num = 1.0 / len;
  2506. this.x *= num;
  2507. this.y *= num;
  2508. this.z *= num;
  2509. return this;
  2510. };
  2511. /**
  2512. * Normalize the current Vector3 to a new vector.
  2513. * @returns the new Vector3.
  2514. */
  2515. Vector3.prototype.normalizeToNew = function () {
  2516. var normalized = new Vector3(0, 0, 0);
  2517. this.normalizeToRef(normalized);
  2518. return normalized;
  2519. };
  2520. /**
  2521. * Normalize the current Vector3 to the reference.
  2522. * @param the reference to update.
  2523. * @returns the updated Vector3.
  2524. */
  2525. Vector3.prototype.normalizeToRef = function (reference) {
  2526. var len = this.length();
  2527. if (len === 0 || len === 1.0) {
  2528. reference.set(this.x, this.y, this.z);
  2529. return reference;
  2530. }
  2531. var scale = 1.0 / len;
  2532. this.scaleToRef(scale, reference);
  2533. return reference;
  2534. };
  2535. /**
  2536. * Returns a new Vector3 copied from the current Vector3.
  2537. */
  2538. Vector3.prototype.clone = function () {
  2539. return new Vector3(this.x, this.y, this.z);
  2540. };
  2541. /**
  2542. * Copies the passed vector coordinates to the current Vector3 ones.
  2543. * Returns the updated Vector3.
  2544. */
  2545. Vector3.prototype.copyFrom = function (source) {
  2546. this.x = source.x;
  2547. this.y = source.y;
  2548. this.z = source.z;
  2549. return this;
  2550. };
  2551. /**
  2552. * Copies the passed floats to the current Vector3 coordinates.
  2553. * Returns the updated Vector3.
  2554. */
  2555. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2556. this.x = x;
  2557. this.y = y;
  2558. this.z = z;
  2559. return this;
  2560. };
  2561. /**
  2562. * Copies the passed floats to the current Vector3 coordinates.
  2563. * Returns the updated Vector3.
  2564. */
  2565. Vector3.prototype.set = function (x, y, z) {
  2566. return this.copyFromFloats(x, y, z);
  2567. };
  2568. // Statics
  2569. /**
  2570. *
  2571. */
  2572. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2573. var d0 = Vector3.Dot(vector0, axis) - size;
  2574. var d1 = Vector3.Dot(vector1, axis) - size;
  2575. var s = d0 / (d0 - d1);
  2576. return s;
  2577. };
  2578. /**
  2579. * Get angle between two vectors.
  2580. * @param vector0 angle between vector0 and vector1
  2581. * @param vector1 angle between vector0 and vector1
  2582. * @param normal direction of the normal.
  2583. * @return the angle between vector0 and vector1.
  2584. */
  2585. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2586. var v0 = vector0.clone().normalize();
  2587. var v1 = vector1.clone().normalize();
  2588. var dot = Vector3.Dot(v0, v1);
  2589. var n = Vector3.Cross(v0, v1);
  2590. if (Vector3.Dot(n, normal) > 0) {
  2591. return Math.acos(dot);
  2592. }
  2593. return -Math.acos(dot);
  2594. };
  2595. /**
  2596. * Returns a new Vector3 set from the index "offset" of the passed array.
  2597. */
  2598. Vector3.FromArray = function (array, offset) {
  2599. if (!offset) {
  2600. offset = 0;
  2601. }
  2602. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2603. };
  2604. /**
  2605. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2606. * This function is deprecated. Use FromArray instead.
  2607. */
  2608. Vector3.FromFloatArray = function (array, offset) {
  2609. return Vector3.FromArray(array, offset);
  2610. };
  2611. /**
  2612. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2613. */
  2614. Vector3.FromArrayToRef = function (array, offset, result) {
  2615. result.x = array[offset];
  2616. result.y = array[offset + 1];
  2617. result.z = array[offset + 2];
  2618. };
  2619. /**
  2620. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2621. * This function is deprecated. Use FromArrayToRef instead.
  2622. */
  2623. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2624. return Vector3.FromArrayToRef(array, offset, result);
  2625. };
  2626. /**
  2627. * Sets the passed vector "result" with the passed floats.
  2628. */
  2629. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2630. result.x = x;
  2631. result.y = y;
  2632. result.z = z;
  2633. };
  2634. /**
  2635. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2636. */
  2637. Vector3.Zero = function () {
  2638. return new Vector3(0.0, 0.0, 0.0);
  2639. };
  2640. /**
  2641. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2642. */
  2643. Vector3.One = function () {
  2644. return new Vector3(1.0, 1.0, 1.0);
  2645. };
  2646. /**
  2647. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2648. */
  2649. Vector3.Up = function () {
  2650. return new Vector3(0.0, 1.0, 0.0);
  2651. };
  2652. /**
  2653. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2654. */
  2655. Vector3.Forward = function () {
  2656. return new Vector3(0.0, 0.0, 1.0);
  2657. };
  2658. /**
  2659. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2660. */
  2661. Vector3.Right = function () {
  2662. return new Vector3(1.0, 0.0, 0.0);
  2663. };
  2664. /**
  2665. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2666. */
  2667. Vector3.Left = function () {
  2668. return new Vector3(-1.0, 0.0, 0.0);
  2669. };
  2670. /**
  2671. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2672. * This method computes tranformed coordinates only, not transformed direction vectors.
  2673. */
  2674. Vector3.TransformCoordinates = function (vector, transformation) {
  2675. var result = Vector3.Zero();
  2676. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2677. return result;
  2678. };
  2679. /**
  2680. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2681. * This method computes tranformed coordinates only, not transformed direction vectors.
  2682. */
  2683. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2684. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2685. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2686. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2687. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2688. result.x = x / w;
  2689. result.y = y / w;
  2690. result.z = z / w;
  2691. };
  2692. /**
  2693. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2694. * This method computes tranformed coordinates only, not transformed direction vectors.
  2695. */
  2696. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2697. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2698. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2699. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2700. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2701. result.x = rx / rw;
  2702. result.y = ry / rw;
  2703. result.z = rz / rw;
  2704. };
  2705. /**
  2706. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2707. * This methods computes transformed normalized direction vectors only.
  2708. */
  2709. Vector3.TransformNormal = function (vector, transformation) {
  2710. var result = Vector3.Zero();
  2711. Vector3.TransformNormalToRef(vector, transformation, result);
  2712. return result;
  2713. };
  2714. /**
  2715. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2716. * This methods computes transformed normalized direction vectors only.
  2717. */
  2718. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2719. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2720. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2721. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2722. result.x = x;
  2723. result.y = y;
  2724. result.z = z;
  2725. };
  2726. /**
  2727. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2728. * This methods computes transformed normalized direction vectors only.
  2729. */
  2730. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2731. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2732. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2733. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2734. };
  2735. /**
  2736. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2737. */
  2738. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2739. var squared = amount * amount;
  2740. var cubed = amount * squared;
  2741. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2742. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2743. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2744. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2745. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2746. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2747. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2748. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2749. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2750. return new Vector3(x, y, z);
  2751. };
  2752. /**
  2753. * 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".
  2754. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2755. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2756. */
  2757. Vector3.Clamp = function (value, min, max) {
  2758. var x = value.x;
  2759. x = (x > max.x) ? max.x : x;
  2760. x = (x < min.x) ? min.x : x;
  2761. var y = value.y;
  2762. y = (y > max.y) ? max.y : y;
  2763. y = (y < min.y) ? min.y : y;
  2764. var z = value.z;
  2765. z = (z > max.z) ? max.z : z;
  2766. z = (z < min.z) ? min.z : z;
  2767. return new Vector3(x, y, z);
  2768. };
  2769. /**
  2770. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2771. */
  2772. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2773. var squared = amount * amount;
  2774. var cubed = amount * squared;
  2775. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2776. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2777. var part3 = (cubed - (2.0 * squared)) + amount;
  2778. var part4 = cubed - squared;
  2779. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2780. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2781. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2782. return new Vector3(x, y, z);
  2783. };
  2784. /**
  2785. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2786. */
  2787. Vector3.Lerp = function (start, end, amount) {
  2788. var result = new Vector3(0, 0, 0);
  2789. Vector3.LerpToRef(start, end, amount, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2794. */
  2795. Vector3.LerpToRef = function (start, end, amount, result) {
  2796. result.x = start.x + ((end.x - start.x) * amount);
  2797. result.y = start.y + ((end.y - start.y) * amount);
  2798. result.z = start.z + ((end.z - start.z) * amount);
  2799. };
  2800. /**
  2801. * Returns the dot product (float) between the vectors "left" and "right".
  2802. */
  2803. Vector3.Dot = function (left, right) {
  2804. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2808. * The cross product is then orthogonal to both "left" and "right".
  2809. */
  2810. Vector3.Cross = function (left, right) {
  2811. var result = Vector3.Zero();
  2812. Vector3.CrossToRef(left, right, result);
  2813. return result;
  2814. };
  2815. /**
  2816. * Sets the passed vector "result" with the cross product of "left" and "right".
  2817. * The cross product is then orthogonal to both "left" and "right".
  2818. */
  2819. Vector3.CrossToRef = function (left, right, result) {
  2820. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2821. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2822. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2823. result.copyFrom(MathTmp.Vector3[0]);
  2824. };
  2825. /**
  2826. * Returns a new Vector3 as the normalization of the passed vector.
  2827. */
  2828. Vector3.Normalize = function (vector) {
  2829. var result = Vector3.Zero();
  2830. Vector3.NormalizeToRef(vector, result);
  2831. return result;
  2832. };
  2833. /**
  2834. * Sets the passed vector "result" with the normalization of the passed first vector.
  2835. */
  2836. Vector3.NormalizeToRef = function (vector, result) {
  2837. result.copyFrom(vector);
  2838. result.normalize();
  2839. };
  2840. Vector3.Project = function (vector, world, transform, viewport) {
  2841. var cw = viewport.width;
  2842. var ch = viewport.height;
  2843. var cx = viewport.x;
  2844. var cy = viewport.y;
  2845. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2846. 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);
  2847. var matrix = MathTmp.Matrix[0];
  2848. world.multiplyToRef(transform, matrix);
  2849. matrix.multiplyToRef(viewportMatrix, matrix);
  2850. return Vector3.TransformCoordinates(vector, matrix);
  2851. };
  2852. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2853. var matrix = MathTmp.Matrix[0];
  2854. world.multiplyToRef(transform, matrix);
  2855. matrix.invert();
  2856. source.x = source.x / viewportWidth * 2 - 1;
  2857. source.y = -(source.y / viewportHeight * 2 - 1);
  2858. var vector = Vector3.TransformCoordinates(source, matrix);
  2859. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2860. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2861. vector = vector.scale(1.0 / num);
  2862. }
  2863. return vector;
  2864. };
  2865. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2866. var result = Vector3.Zero();
  2867. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2868. return result;
  2869. };
  2870. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2871. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2872. };
  2873. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2874. var matrix = MathTmp.Matrix[0];
  2875. world.multiplyToRef(view, matrix);
  2876. matrix.multiplyToRef(projection, matrix);
  2877. matrix.invert();
  2878. var screenSource = MathTmp.Vector3[0];
  2879. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2880. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2881. screenSource.z = 2 * sourceZ - 1.0;
  2882. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2883. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2884. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2885. result.scaleInPlace(1.0 / num);
  2886. }
  2887. };
  2888. Vector3.Minimize = function (left, right) {
  2889. var min = left.clone();
  2890. min.MinimizeInPlace(right);
  2891. return min;
  2892. };
  2893. Vector3.Maximize = function (left, right) {
  2894. var max = left.clone();
  2895. max.MaximizeInPlace(right);
  2896. return max;
  2897. };
  2898. /**
  2899. * Returns the distance (float) between the vectors "value1" and "value2".
  2900. */
  2901. Vector3.Distance = function (value1, value2) {
  2902. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2903. };
  2904. /**
  2905. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2906. */
  2907. Vector3.DistanceSquared = function (value1, value2) {
  2908. var x = value1.x - value2.x;
  2909. var y = value1.y - value2.y;
  2910. var z = value1.z - value2.z;
  2911. return (x * x) + (y * y) + (z * z);
  2912. };
  2913. /**
  2914. * Returns a new Vector3 located at the center between "value1" and "value2".
  2915. */
  2916. Vector3.Center = function (value1, value2) {
  2917. var center = value1.add(value2);
  2918. center.scaleInPlace(0.5);
  2919. return center;
  2920. };
  2921. /**
  2922. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2923. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2924. * to something in order to rotate it from its local system to the given target system.
  2925. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2926. * Returns a new Vector3.
  2927. */
  2928. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2929. var rotation = Vector3.Zero();
  2930. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2931. return rotation;
  2932. };
  2933. /**
  2934. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2935. */
  2936. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2937. var quat = MathTmp.Quaternion[0];
  2938. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2939. quat.toEulerAnglesToRef(ref);
  2940. };
  2941. return Vector3;
  2942. }());
  2943. BABYLON.Vector3 = Vector3;
  2944. //Vector4 class created for EulerAngle class conversion to Quaternion
  2945. var Vector4 = /** @class */ (function () {
  2946. /**
  2947. * Creates a Vector4 object from the passed floats.
  2948. */
  2949. function Vector4(x, y, z, w) {
  2950. this.x = x;
  2951. this.y = y;
  2952. this.z = z;
  2953. this.w = w;
  2954. }
  2955. /**
  2956. * Returns the string with the Vector4 coordinates.
  2957. */
  2958. Vector4.prototype.toString = function () {
  2959. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2960. };
  2961. /**
  2962. * Returns the string "Vector4".
  2963. */
  2964. Vector4.prototype.getClassName = function () {
  2965. return "Vector4";
  2966. };
  2967. /**
  2968. * Returns the Vector4 hash code.
  2969. */
  2970. Vector4.prototype.getHashCode = function () {
  2971. var hash = this.x || 0;
  2972. hash = (hash * 397) ^ (this.y || 0);
  2973. hash = (hash * 397) ^ (this.z || 0);
  2974. hash = (hash * 397) ^ (this.w || 0);
  2975. return hash;
  2976. };
  2977. // Operators
  2978. /**
  2979. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2980. */
  2981. Vector4.prototype.asArray = function () {
  2982. var result = new Array();
  2983. this.toArray(result, 0);
  2984. return result;
  2985. };
  2986. /**
  2987. * Populates the passed array from the passed index with the Vector4 coordinates.
  2988. * Returns the Vector4.
  2989. */
  2990. Vector4.prototype.toArray = function (array, index) {
  2991. if (index === undefined) {
  2992. index = 0;
  2993. }
  2994. array[index] = this.x;
  2995. array[index + 1] = this.y;
  2996. array[index + 2] = this.z;
  2997. array[index + 3] = this.w;
  2998. return this;
  2999. };
  3000. /**
  3001. * Adds the passed vector to the current Vector4.
  3002. * Returns the updated Vector4.
  3003. */
  3004. Vector4.prototype.addInPlace = function (otherVector) {
  3005. this.x += otherVector.x;
  3006. this.y += otherVector.y;
  3007. this.z += otherVector.z;
  3008. this.w += otherVector.w;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3013. */
  3014. Vector4.prototype.add = function (otherVector) {
  3015. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3016. };
  3017. /**
  3018. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3019. * Returns the current Vector4.
  3020. */
  3021. Vector4.prototype.addToRef = function (otherVector, result) {
  3022. result.x = this.x + otherVector.x;
  3023. result.y = this.y + otherVector.y;
  3024. result.z = this.z + otherVector.z;
  3025. result.w = this.w + otherVector.w;
  3026. return this;
  3027. };
  3028. /**
  3029. * Subtract in place the passed vector from the current Vector4.
  3030. * Returns the updated Vector4.
  3031. */
  3032. Vector4.prototype.subtractInPlace = function (otherVector) {
  3033. this.x -= otherVector.x;
  3034. this.y -= otherVector.y;
  3035. this.z -= otherVector.z;
  3036. this.w -= otherVector.w;
  3037. return this;
  3038. };
  3039. /**
  3040. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3041. */
  3042. Vector4.prototype.subtract = function (otherVector) {
  3043. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3044. };
  3045. /**
  3046. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3047. * Returns the current Vector4.
  3048. */
  3049. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3050. result.x = this.x - otherVector.x;
  3051. result.y = this.y - otherVector.y;
  3052. result.z = this.z - otherVector.z;
  3053. result.w = this.w - otherVector.w;
  3054. return this;
  3055. };
  3056. /**
  3057. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3058. */
  3059. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3060. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3061. };
  3062. /**
  3063. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3064. * Returns the current Vector4.
  3065. */
  3066. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3067. result.x = this.x - x;
  3068. result.y = this.y - y;
  3069. result.z = this.z - z;
  3070. result.w = this.w - w;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3075. */
  3076. Vector4.prototype.negate = function () {
  3077. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3078. };
  3079. /**
  3080. * Multiplies the current Vector4 coordinates by scale (float).
  3081. * Returns the updated Vector4.
  3082. */
  3083. Vector4.prototype.scaleInPlace = function (scale) {
  3084. this.x *= scale;
  3085. this.y *= scale;
  3086. this.z *= scale;
  3087. this.w *= scale;
  3088. return this;
  3089. };
  3090. /**
  3091. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3092. */
  3093. Vector4.prototype.scale = function (scale) {
  3094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3095. };
  3096. /**
  3097. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3098. * Returns the current Vector4.
  3099. */
  3100. Vector4.prototype.scaleToRef = function (scale, result) {
  3101. result.x = this.x * scale;
  3102. result.y = this.y * scale;
  3103. result.z = this.z * scale;
  3104. result.w = this.w * scale;
  3105. return this;
  3106. };
  3107. /**
  3108. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3109. */
  3110. Vector4.prototype.equals = function (otherVector) {
  3111. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3112. };
  3113. /**
  3114. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3115. */
  3116. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3117. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3118. return otherVector
  3119. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3120. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3121. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3122. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3123. };
  3124. /**
  3125. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3126. */
  3127. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3128. return this.x === x && this.y === y && this.z === z && this.w === w;
  3129. };
  3130. /**
  3131. * Multiplies in place the current Vector4 by the passed one.
  3132. * Returns the updated Vector4.
  3133. */
  3134. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3135. this.x *= otherVector.x;
  3136. this.y *= otherVector.y;
  3137. this.z *= otherVector.z;
  3138. this.w *= otherVector.w;
  3139. return this;
  3140. };
  3141. /**
  3142. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3143. */
  3144. Vector4.prototype.multiply = function (otherVector) {
  3145. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3146. };
  3147. /**
  3148. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3149. * Returns the current Vector4.
  3150. */
  3151. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3152. result.x = this.x * otherVector.x;
  3153. result.y = this.y * otherVector.y;
  3154. result.z = this.z * otherVector.z;
  3155. result.w = this.w * otherVector.w;
  3156. return this;
  3157. };
  3158. /**
  3159. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3160. */
  3161. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3162. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3163. };
  3164. /**
  3165. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3166. */
  3167. Vector4.prototype.divide = function (otherVector) {
  3168. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3169. };
  3170. /**
  3171. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3172. * Returns the current Vector4.
  3173. */
  3174. Vector4.prototype.divideToRef = function (otherVector, result) {
  3175. result.x = this.x / otherVector.x;
  3176. result.y = this.y / otherVector.y;
  3177. result.z = this.z / otherVector.z;
  3178. result.w = this.w / otherVector.w;
  3179. return this;
  3180. };
  3181. /**
  3182. * Divides the current Vector3 coordinates by the passed ones.
  3183. * Returns the updated Vector3.
  3184. */
  3185. Vector4.prototype.divideInPlace = function (otherVector) {
  3186. return this.divideToRef(otherVector, this);
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MinimizeInPlace = function (other) {
  3192. if (other.x < this.x)
  3193. this.x = other.x;
  3194. if (other.y < this.y)
  3195. this.y = other.y;
  3196. if (other.z < this.z)
  3197. this.z = other.z;
  3198. if (other.w < this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. /**
  3203. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3204. */
  3205. Vector4.prototype.MaximizeInPlace = function (other) {
  3206. if (other.x > this.x)
  3207. this.x = other.x;
  3208. if (other.y > this.y)
  3209. this.y = other.y;
  3210. if (other.z > this.z)
  3211. this.z = other.z;
  3212. if (other.w > this.w)
  3213. this.w = other.w;
  3214. return this;
  3215. };
  3216. // Properties
  3217. /**
  3218. * Returns the Vector4 length (float).
  3219. */
  3220. Vector4.prototype.length = function () {
  3221. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3222. };
  3223. /**
  3224. * Returns the Vector4 squared length (float).
  3225. */
  3226. Vector4.prototype.lengthSquared = function () {
  3227. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3228. };
  3229. // Methods
  3230. /**
  3231. * Normalizes in place the Vector4.
  3232. * Returns the updated Vector4.
  3233. */
  3234. Vector4.prototype.normalize = function () {
  3235. var len = this.length();
  3236. if (len === 0)
  3237. return this;
  3238. var num = 1.0 / len;
  3239. this.x *= num;
  3240. this.y *= num;
  3241. this.z *= num;
  3242. this.w *= num;
  3243. return this;
  3244. };
  3245. /**
  3246. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3247. */
  3248. Vector4.prototype.toVector3 = function () {
  3249. return new Vector3(this.x, this.y, this.z);
  3250. };
  3251. /**
  3252. * Returns a new Vector4 copied from the current one.
  3253. */
  3254. Vector4.prototype.clone = function () {
  3255. return new Vector4(this.x, this.y, this.z, this.w);
  3256. };
  3257. /**
  3258. * Updates the current Vector4 with the passed one coordinates.
  3259. * Returns the updated Vector4.
  3260. */
  3261. Vector4.prototype.copyFrom = function (source) {
  3262. this.x = source.x;
  3263. this.y = source.y;
  3264. this.z = source.z;
  3265. this.w = source.w;
  3266. return this;
  3267. };
  3268. /**
  3269. * Updates the current Vector4 coordinates with the passed floats.
  3270. * Returns the updated Vector4.
  3271. */
  3272. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3273. this.x = x;
  3274. this.y = y;
  3275. this.z = z;
  3276. this.w = w;
  3277. return this;
  3278. };
  3279. /**
  3280. * Updates the current Vector4 coordinates with the passed floats.
  3281. * Returns the updated Vector4.
  3282. */
  3283. Vector4.prototype.set = function (x, y, z, w) {
  3284. return this.copyFromFloats(x, y, z, w);
  3285. };
  3286. // Statics
  3287. /**
  3288. * Returns a new Vector4 set from the starting index of the passed array.
  3289. */
  3290. Vector4.FromArray = function (array, offset) {
  3291. if (!offset) {
  3292. offset = 0;
  3293. }
  3294. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3295. };
  3296. /**
  3297. * Updates the passed vector "result" from the starting index of the passed array.
  3298. */
  3299. Vector4.FromArrayToRef = function (array, offset, result) {
  3300. result.x = array[offset];
  3301. result.y = array[offset + 1];
  3302. result.z = array[offset + 2];
  3303. result.w = array[offset + 3];
  3304. };
  3305. /**
  3306. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3307. */
  3308. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3309. Vector4.FromArrayToRef(array, offset, result);
  3310. };
  3311. /**
  3312. * Updates the passed vector "result" coordinates from the passed floats.
  3313. */
  3314. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3315. result.x = x;
  3316. result.y = y;
  3317. result.z = z;
  3318. result.w = w;
  3319. };
  3320. /**
  3321. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3322. */
  3323. Vector4.Zero = function () {
  3324. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3328. */
  3329. Vector4.One = function () {
  3330. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3331. };
  3332. /**
  3333. * Returns a new normalized Vector4 from the passed one.
  3334. */
  3335. Vector4.Normalize = function (vector) {
  3336. var result = Vector4.Zero();
  3337. Vector4.NormalizeToRef(vector, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Updates the passed vector "result" from the normalization of the passed one.
  3342. */
  3343. Vector4.NormalizeToRef = function (vector, result) {
  3344. result.copyFrom(vector);
  3345. result.normalize();
  3346. };
  3347. Vector4.Minimize = function (left, right) {
  3348. var min = left.clone();
  3349. min.MinimizeInPlace(right);
  3350. return min;
  3351. };
  3352. Vector4.Maximize = function (left, right) {
  3353. var max = left.clone();
  3354. max.MaximizeInPlace(right);
  3355. return max;
  3356. };
  3357. /**
  3358. * Returns the distance (float) between the vectors "value1" and "value2".
  3359. */
  3360. Vector4.Distance = function (value1, value2) {
  3361. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3362. };
  3363. /**
  3364. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3365. */
  3366. Vector4.DistanceSquared = function (value1, value2) {
  3367. var x = value1.x - value2.x;
  3368. var y = value1.y - value2.y;
  3369. var z = value1.z - value2.z;
  3370. var w = value1.w - value2.w;
  3371. return (x * x) + (y * y) + (z * z) + (w * w);
  3372. };
  3373. /**
  3374. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3375. */
  3376. Vector4.Center = function (value1, value2) {
  3377. var center = value1.add(value2);
  3378. center.scaleInPlace(0.5);
  3379. return center;
  3380. };
  3381. /**
  3382. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3383. * This methods computes transformed normalized direction vectors only.
  3384. */
  3385. Vector4.TransformNormal = function (vector, transformation) {
  3386. var result = Vector4.Zero();
  3387. Vector4.TransformNormalToRef(vector, transformation, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3392. * This methods computes transformed normalized direction vectors only.
  3393. */
  3394. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3395. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3396. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3397. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3398. result.x = x;
  3399. result.y = y;
  3400. result.z = z;
  3401. result.w = vector.w;
  3402. };
  3403. /**
  3404. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3405. * This methods computes transformed normalized direction vectors only.
  3406. */
  3407. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3408. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3409. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3410. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3411. result.w = w;
  3412. };
  3413. return Vector4;
  3414. }());
  3415. BABYLON.Vector4 = Vector4;
  3416. var Size = /** @class */ (function () {
  3417. /**
  3418. * Creates a Size object from the passed width and height (floats).
  3419. */
  3420. function Size(width, height) {
  3421. this.width = width;
  3422. this.height = height;
  3423. }
  3424. // Returns a string with the Size width and height.
  3425. Size.prototype.toString = function () {
  3426. return "{W: " + this.width + ", H: " + this.height + "}";
  3427. };
  3428. /**
  3429. * Returns the string "Size"
  3430. */
  3431. Size.prototype.getClassName = function () {
  3432. return "Size";
  3433. };
  3434. /**
  3435. * Returns the Size hash code.
  3436. */
  3437. Size.prototype.getHashCode = function () {
  3438. var hash = this.width || 0;
  3439. hash = (hash * 397) ^ (this.height || 0);
  3440. return hash;
  3441. };
  3442. /**
  3443. * Updates the current size from the passed one.
  3444. * Returns the updated Size.
  3445. */
  3446. Size.prototype.copyFrom = function (src) {
  3447. this.width = src.width;
  3448. this.height = src.height;
  3449. };
  3450. /**
  3451. * Updates in place the current Size from the passed floats.
  3452. * Returns the updated Size.
  3453. */
  3454. Size.prototype.copyFromFloats = function (width, height) {
  3455. this.width = width;
  3456. this.height = height;
  3457. return this;
  3458. };
  3459. /**
  3460. * Updates in place the current Size from the passed floats.
  3461. * Returns the updated Size.
  3462. */
  3463. Size.prototype.set = function (width, height) {
  3464. return this.copyFromFloats(width, height);
  3465. };
  3466. /**
  3467. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3468. */
  3469. Size.prototype.multiplyByFloats = function (w, h) {
  3470. return new Size(this.width * w, this.height * h);
  3471. };
  3472. /**
  3473. * Returns a new Size copied from the passed one.
  3474. */
  3475. Size.prototype.clone = function () {
  3476. return new Size(this.width, this.height);
  3477. };
  3478. /**
  3479. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3480. */
  3481. Size.prototype.equals = function (other) {
  3482. if (!other) {
  3483. return false;
  3484. }
  3485. return (this.width === other.width) && (this.height === other.height);
  3486. };
  3487. Object.defineProperty(Size.prototype, "surface", {
  3488. /**
  3489. * Returns the surface of the Size : width * height (float).
  3490. */
  3491. get: function () {
  3492. return this.width * this.height;
  3493. },
  3494. enumerable: true,
  3495. configurable: true
  3496. });
  3497. /**
  3498. * Returns a new Size set to (0.0, 0.0)
  3499. */
  3500. Size.Zero = function () {
  3501. return new Size(0.0, 0.0);
  3502. };
  3503. /**
  3504. * Returns a new Size set as the addition result of the current Size and the passed one.
  3505. */
  3506. Size.prototype.add = function (otherSize) {
  3507. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3508. return r;
  3509. };
  3510. /**
  3511. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3512. */
  3513. Size.prototype.subtract = function (otherSize) {
  3514. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3515. return r;
  3516. };
  3517. /**
  3518. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3519. */
  3520. Size.Lerp = function (start, end, amount) {
  3521. var w = start.width + ((end.width - start.width) * amount);
  3522. var h = start.height + ((end.height - start.height) * amount);
  3523. return new Size(w, h);
  3524. };
  3525. return Size;
  3526. }());
  3527. BABYLON.Size = Size;
  3528. var Quaternion = /** @class */ (function () {
  3529. /**
  3530. * Creates a new Quaternion from the passed floats.
  3531. */
  3532. function Quaternion(x, y, z, w) {
  3533. if (x === void 0) { x = 0.0; }
  3534. if (y === void 0) { y = 0.0; }
  3535. if (z === void 0) { z = 0.0; }
  3536. if (w === void 0) { w = 1.0; }
  3537. this.x = x;
  3538. this.y = y;
  3539. this.z = z;
  3540. this.w = w;
  3541. }
  3542. /**
  3543. * Returns a string with the Quaternion coordinates.
  3544. */
  3545. Quaternion.prototype.toString = function () {
  3546. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3547. };
  3548. /**
  3549. * Returns the string "Quaternion".
  3550. */
  3551. Quaternion.prototype.getClassName = function () {
  3552. return "Quaternion";
  3553. };
  3554. /**
  3555. * Returns the Quaternion hash code.
  3556. */
  3557. Quaternion.prototype.getHashCode = function () {
  3558. var hash = this.x || 0;
  3559. hash = (hash * 397) ^ (this.y || 0);
  3560. hash = (hash * 397) ^ (this.z || 0);
  3561. hash = (hash * 397) ^ (this.w || 0);
  3562. return hash;
  3563. };
  3564. /**
  3565. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3566. */
  3567. Quaternion.prototype.asArray = function () {
  3568. return [this.x, this.y, this.z, this.w];
  3569. };
  3570. /**
  3571. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3572. */
  3573. Quaternion.prototype.equals = function (otherQuaternion) {
  3574. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3575. };
  3576. /**
  3577. * Returns a new Quaternion copied from the current one.
  3578. */
  3579. Quaternion.prototype.clone = function () {
  3580. return new Quaternion(this.x, this.y, this.z, this.w);
  3581. };
  3582. /**
  3583. * Updates the current Quaternion from the passed one coordinates.
  3584. * Returns the updated Quaterion.
  3585. */
  3586. Quaternion.prototype.copyFrom = function (other) {
  3587. this.x = other.x;
  3588. this.y = other.y;
  3589. this.z = other.z;
  3590. this.w = other.w;
  3591. return this;
  3592. };
  3593. /**
  3594. * Updates the current Quaternion from the passed float coordinates.
  3595. * Returns the updated Quaterion.
  3596. */
  3597. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3598. this.x = x;
  3599. this.y = y;
  3600. this.z = z;
  3601. this.w = w;
  3602. return this;
  3603. };
  3604. /**
  3605. * Updates the current Quaternion from the passed float coordinates.
  3606. * Returns the updated Quaterion.
  3607. */
  3608. Quaternion.prototype.set = function (x, y, z, w) {
  3609. return this.copyFromFloats(x, y, z, w);
  3610. };
  3611. /**
  3612. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3613. */
  3614. Quaternion.prototype.add = function (other) {
  3615. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3616. };
  3617. /**
  3618. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3619. */
  3620. Quaternion.prototype.subtract = function (other) {
  3621. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3622. };
  3623. /**
  3624. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3625. */
  3626. Quaternion.prototype.scale = function (value) {
  3627. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3628. };
  3629. /**
  3630. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3631. */
  3632. Quaternion.prototype.multiply = function (q1) {
  3633. var result = new Quaternion(0, 0, 0, 1.0);
  3634. this.multiplyToRef(q1, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3639. * Returns the current Quaternion.
  3640. */
  3641. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3642. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3643. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3644. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3645. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3646. result.copyFromFloats(x, y, z, w);
  3647. return this;
  3648. };
  3649. /**
  3650. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3651. * Returns the updated Quaternion.
  3652. */
  3653. Quaternion.prototype.multiplyInPlace = function (q1) {
  3654. this.multiplyToRef(q1, this);
  3655. return this;
  3656. };
  3657. /**
  3658. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3659. * Returns the current Quaternion.
  3660. */
  3661. Quaternion.prototype.conjugateToRef = function (ref) {
  3662. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3663. return this;
  3664. };
  3665. /**
  3666. * Conjugates in place the current Quaternion.
  3667. * Returns the updated Quaternion.
  3668. */
  3669. Quaternion.prototype.conjugateInPlace = function () {
  3670. this.x *= -1;
  3671. this.y *= -1;
  3672. this.z *= -1;
  3673. return this;
  3674. };
  3675. /**
  3676. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3677. */
  3678. Quaternion.prototype.conjugate = function () {
  3679. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3680. return result;
  3681. };
  3682. /**
  3683. * Returns the Quaternion length (float).
  3684. */
  3685. Quaternion.prototype.length = function () {
  3686. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3687. };
  3688. /**
  3689. * Normalize in place the current Quaternion.
  3690. * Returns the updated Quaternion.
  3691. */
  3692. Quaternion.prototype.normalize = function () {
  3693. var length = 1.0 / this.length();
  3694. this.x *= length;
  3695. this.y *= length;
  3696. this.z *= length;
  3697. this.w *= length;
  3698. return this;
  3699. };
  3700. /**
  3701. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3702. */
  3703. Quaternion.prototype.toEulerAngles = function (order) {
  3704. if (order === void 0) { order = "YZX"; }
  3705. var result = Vector3.Zero();
  3706. this.toEulerAnglesToRef(result, order);
  3707. return result;
  3708. };
  3709. /**
  3710. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3711. * Returns the current Quaternion.
  3712. */
  3713. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3714. if (order === void 0) { order = "YZX"; }
  3715. var qz = this.z;
  3716. var qx = this.x;
  3717. var qy = this.y;
  3718. var qw = this.w;
  3719. var sqw = qw * qw;
  3720. var sqz = qz * qz;
  3721. var sqx = qx * qx;
  3722. var sqy = qy * qy;
  3723. var zAxisY = qy * qz - qx * qw;
  3724. var limit = .4999999;
  3725. if (zAxisY < -limit) {
  3726. result.y = 2 * Math.atan2(qy, qw);
  3727. result.x = Math.PI / 2;
  3728. result.z = 0;
  3729. }
  3730. else if (zAxisY > limit) {
  3731. result.y = 2 * Math.atan2(qy, qw);
  3732. result.x = -Math.PI / 2;
  3733. result.z = 0;
  3734. }
  3735. else {
  3736. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3737. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3738. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3739. }
  3740. return this;
  3741. };
  3742. /**
  3743. * Updates the passed rotation matrix with the current Quaternion values.
  3744. * Returns the current Quaternion.
  3745. */
  3746. Quaternion.prototype.toRotationMatrix = function (result) {
  3747. var xx = this.x * this.x;
  3748. var yy = this.y * this.y;
  3749. var zz = this.z * this.z;
  3750. var xy = this.x * this.y;
  3751. var zw = this.z * this.w;
  3752. var zx = this.z * this.x;
  3753. var yw = this.y * this.w;
  3754. var yz = this.y * this.z;
  3755. var xw = this.x * this.w;
  3756. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3757. result.m[1] = 2.0 * (xy + zw);
  3758. result.m[2] = 2.0 * (zx - yw);
  3759. result.m[3] = 0;
  3760. result.m[4] = 2.0 * (xy - zw);
  3761. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3762. result.m[6] = 2.0 * (yz + xw);
  3763. result.m[7] = 0;
  3764. result.m[8] = 2.0 * (zx + yw);
  3765. result.m[9] = 2.0 * (yz - xw);
  3766. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3767. result.m[11] = 0;
  3768. result.m[12] = 0;
  3769. result.m[13] = 0;
  3770. result.m[14] = 0;
  3771. result.m[15] = 1.0;
  3772. result._markAsUpdated();
  3773. return this;
  3774. };
  3775. /**
  3776. * Updates the current Quaternion from the passed rotation matrix values.
  3777. * Returns the updated Quaternion.
  3778. */
  3779. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3780. Quaternion.FromRotationMatrixToRef(matrix, this);
  3781. return this;
  3782. };
  3783. // Statics
  3784. /**
  3785. * Returns a new Quaternion set from the passed rotation matrix values.
  3786. */
  3787. Quaternion.FromRotationMatrix = function (matrix) {
  3788. var result = new Quaternion();
  3789. Quaternion.FromRotationMatrixToRef(matrix, result);
  3790. return result;
  3791. };
  3792. /**
  3793. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3794. */
  3795. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3796. var data = matrix.m;
  3797. var m11 = data[0], m12 = data[4], m13 = data[8];
  3798. var m21 = data[1], m22 = data[5], m23 = data[9];
  3799. var m31 = data[2], m32 = data[6], m33 = data[10];
  3800. var trace = m11 + m22 + m33;
  3801. var s;
  3802. if (trace > 0) {
  3803. s = 0.5 / Math.sqrt(trace + 1.0);
  3804. result.w = 0.25 / s;
  3805. result.x = (m32 - m23) * s;
  3806. result.y = (m13 - m31) * s;
  3807. result.z = (m21 - m12) * s;
  3808. }
  3809. else if (m11 > m22 && m11 > m33) {
  3810. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3811. result.w = (m32 - m23) / s;
  3812. result.x = 0.25 * s;
  3813. result.y = (m12 + m21) / s;
  3814. result.z = (m13 + m31) / s;
  3815. }
  3816. else if (m22 > m33) {
  3817. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3818. result.w = (m13 - m31) / s;
  3819. result.x = (m12 + m21) / s;
  3820. result.y = 0.25 * s;
  3821. result.z = (m23 + m32) / s;
  3822. }
  3823. else {
  3824. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3825. result.w = (m21 - m12) / s;
  3826. result.x = (m13 + m31) / s;
  3827. result.y = (m23 + m32) / s;
  3828. result.z = 0.25 * s;
  3829. }
  3830. };
  3831. /**
  3832. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3833. */
  3834. Quaternion.Zero = function () {
  3835. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3836. };
  3837. /**
  3838. * Returns a new Quaternion as the inverted current Quaternion.
  3839. */
  3840. Quaternion.Inverse = function (q) {
  3841. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3842. };
  3843. /**
  3844. * Returns the identity Quaternion.
  3845. */
  3846. Quaternion.Identity = function () {
  3847. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3848. };
  3849. Quaternion.IsIdentity = function (quaternion) {
  3850. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3851. };
  3852. /**
  3853. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3854. */
  3855. Quaternion.RotationAxis = function (axis, angle) {
  3856. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3857. };
  3858. /**
  3859. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3860. */
  3861. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3862. var sin = Math.sin(angle / 2);
  3863. axis.normalize();
  3864. result.w = Math.cos(angle / 2);
  3865. result.x = axis.x * sin;
  3866. result.y = axis.y * sin;
  3867. result.z = axis.z * sin;
  3868. return result;
  3869. };
  3870. /**
  3871. * Retuns a new Quaternion set from the starting index of the passed array.
  3872. */
  3873. Quaternion.FromArray = function (array, offset) {
  3874. if (!offset) {
  3875. offset = 0;
  3876. }
  3877. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3878. };
  3879. /**
  3880. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3881. */
  3882. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3883. var q = new Quaternion();
  3884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3885. return q;
  3886. };
  3887. /**
  3888. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3889. */
  3890. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3891. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3892. var halfRoll = roll * 0.5;
  3893. var halfPitch = pitch * 0.5;
  3894. var halfYaw = yaw * 0.5;
  3895. var sinRoll = Math.sin(halfRoll);
  3896. var cosRoll = Math.cos(halfRoll);
  3897. var sinPitch = Math.sin(halfPitch);
  3898. var cosPitch = Math.cos(halfPitch);
  3899. var sinYaw = Math.sin(halfYaw);
  3900. var cosYaw = Math.cos(halfYaw);
  3901. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3902. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3903. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3904. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3905. };
  3906. /**
  3907. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3908. */
  3909. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3910. var result = new Quaternion();
  3911. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3912. return result;
  3913. };
  3914. /**
  3915. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3916. */
  3917. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3918. // Produces a quaternion from Euler angles in the z-x-z orientation
  3919. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3920. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3921. var halfBeta = beta * 0.5;
  3922. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3923. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3924. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3925. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3926. };
  3927. /**
  3928. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3929. * cf to Vector3.RotationFromAxis() documentation.
  3930. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3931. */
  3932. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3933. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3934. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3935. return quat;
  3936. };
  3937. /**
  3938. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3939. * cf to Vector3.RotationFromAxis() documentation.
  3940. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3941. */
  3942. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3943. var rotMat = MathTmp.Matrix[0];
  3944. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3945. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3946. };
  3947. Quaternion.Slerp = function (left, right, amount) {
  3948. var result = Quaternion.Identity();
  3949. Quaternion.SlerpToRef(left, right, amount, result);
  3950. return result;
  3951. };
  3952. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3953. var num2;
  3954. var num3;
  3955. var num = amount;
  3956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3957. var flag = false;
  3958. if (num4 < 0) {
  3959. flag = true;
  3960. num4 = -num4;
  3961. }
  3962. if (num4 > 0.999999) {
  3963. num3 = 1 - num;
  3964. num2 = flag ? -num : num;
  3965. }
  3966. else {
  3967. var num5 = Math.acos(num4);
  3968. var num6 = (1.0 / Math.sin(num5));
  3969. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3970. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3971. }
  3972. result.x = (num3 * left.x) + (num2 * right.x);
  3973. result.y = (num3 * left.y) + (num2 * right.y);
  3974. result.z = (num3 * left.z) + (num2 * right.z);
  3975. result.w = (num3 * left.w) + (num2 * right.w);
  3976. };
  3977. /**
  3978. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3979. */
  3980. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3981. var squared = amount * amount;
  3982. var cubed = amount * squared;
  3983. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3984. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3985. var part3 = (cubed - (2.0 * squared)) + amount;
  3986. var part4 = cubed - squared;
  3987. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3988. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3989. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3990. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3991. return new Quaternion(x, y, z, w);
  3992. };
  3993. return Quaternion;
  3994. }());
  3995. BABYLON.Quaternion = Quaternion;
  3996. var Matrix = /** @class */ (function () {
  3997. function Matrix() {
  3998. this._isIdentity = false;
  3999. this._isIdentityDirty = true;
  4000. this.m = new Float32Array(16);
  4001. this._markAsUpdated();
  4002. }
  4003. Matrix.prototype._markAsUpdated = function () {
  4004. this.updateFlag = Matrix._updateFlagSeed++;
  4005. this._isIdentityDirty = true;
  4006. };
  4007. // Properties
  4008. /**
  4009. * Boolean : True is the matrix is the identity matrix
  4010. */
  4011. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4012. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4013. if (this._isIdentityDirty) {
  4014. this._isIdentityDirty = false;
  4015. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4016. this._isIdentity = false;
  4017. }
  4018. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4019. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4020. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4021. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4022. this._isIdentity = false;
  4023. }
  4024. else {
  4025. this._isIdentity = true;
  4026. }
  4027. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4028. this._isIdentity = false;
  4029. }
  4030. }
  4031. return this._isIdentity;
  4032. };
  4033. /**
  4034. * Returns the matrix determinant (float).
  4035. */
  4036. Matrix.prototype.determinant = function () {
  4037. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4038. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4039. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4040. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4041. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4042. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4043. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4044. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4045. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4046. };
  4047. // Methods
  4048. /**
  4049. * Returns the matrix underlying array.
  4050. */
  4051. Matrix.prototype.toArray = function () {
  4052. return this.m;
  4053. };
  4054. /**
  4055. * Returns the matrix underlying array.
  4056. */
  4057. Matrix.prototype.asArray = function () {
  4058. return this.toArray();
  4059. };
  4060. /**
  4061. * Inverts in place the Matrix.
  4062. * Returns the Matrix inverted.
  4063. */
  4064. Matrix.prototype.invert = function () {
  4065. this.invertToRef(this);
  4066. return this;
  4067. };
  4068. /**
  4069. * Sets all the matrix elements to zero.
  4070. * Returns the Matrix.
  4071. */
  4072. Matrix.prototype.reset = function () {
  4073. for (var index = 0; index < 16; index++) {
  4074. this.m[index] = 0.0;
  4075. }
  4076. this._markAsUpdated();
  4077. return this;
  4078. };
  4079. /**
  4080. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4081. */
  4082. Matrix.prototype.add = function (other) {
  4083. var result = new Matrix();
  4084. this.addToRef(other, result);
  4085. return result;
  4086. };
  4087. /**
  4088. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4089. * Returns the Matrix.
  4090. */
  4091. Matrix.prototype.addToRef = function (other, result) {
  4092. for (var index = 0; index < 16; index++) {
  4093. result.m[index] = this.m[index] + other.m[index];
  4094. }
  4095. result._markAsUpdated();
  4096. return this;
  4097. };
  4098. /**
  4099. * Adds in place the passed matrix to the current Matrix.
  4100. * Returns the updated Matrix.
  4101. */
  4102. Matrix.prototype.addToSelf = function (other) {
  4103. for (var index = 0; index < 16; index++) {
  4104. this.m[index] += other.m[index];
  4105. }
  4106. this._markAsUpdated();
  4107. return this;
  4108. };
  4109. /**
  4110. * Sets the passed matrix with the current inverted Matrix.
  4111. * Returns the unmodified current Matrix.
  4112. */
  4113. Matrix.prototype.invertToRef = function (other) {
  4114. var l1 = this.m[0];
  4115. var l2 = this.m[1];
  4116. var l3 = this.m[2];
  4117. var l4 = this.m[3];
  4118. var l5 = this.m[4];
  4119. var l6 = this.m[5];
  4120. var l7 = this.m[6];
  4121. var l8 = this.m[7];
  4122. var l9 = this.m[8];
  4123. var l10 = this.m[9];
  4124. var l11 = this.m[10];
  4125. var l12 = this.m[11];
  4126. var l13 = this.m[12];
  4127. var l14 = this.m[13];
  4128. var l15 = this.m[14];
  4129. var l16 = this.m[15];
  4130. var l17 = (l11 * l16) - (l12 * l15);
  4131. var l18 = (l10 * l16) - (l12 * l14);
  4132. var l19 = (l10 * l15) - (l11 * l14);
  4133. var l20 = (l9 * l16) - (l12 * l13);
  4134. var l21 = (l9 * l15) - (l11 * l13);
  4135. var l22 = (l9 * l14) - (l10 * l13);
  4136. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4137. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4138. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4139. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4140. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4141. var l28 = (l7 * l16) - (l8 * l15);
  4142. var l29 = (l6 * l16) - (l8 * l14);
  4143. var l30 = (l6 * l15) - (l7 * l14);
  4144. var l31 = (l5 * l16) - (l8 * l13);
  4145. var l32 = (l5 * l15) - (l7 * l13);
  4146. var l33 = (l5 * l14) - (l6 * l13);
  4147. var l34 = (l7 * l12) - (l8 * l11);
  4148. var l35 = (l6 * l12) - (l8 * l10);
  4149. var l36 = (l6 * l11) - (l7 * l10);
  4150. var l37 = (l5 * l12) - (l8 * l9);
  4151. var l38 = (l5 * l11) - (l7 * l9);
  4152. var l39 = (l5 * l10) - (l6 * l9);
  4153. other.m[0] = l23 * l27;
  4154. other.m[4] = l24 * l27;
  4155. other.m[8] = l25 * l27;
  4156. other.m[12] = l26 * l27;
  4157. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4158. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4159. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4160. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4161. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4162. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4163. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4164. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4165. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4166. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4167. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4168. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4169. other._markAsUpdated();
  4170. return this;
  4171. };
  4172. /**
  4173. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4174. * Returns the updated Matrix.
  4175. */
  4176. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4177. this.m[12] = x;
  4178. this.m[13] = y;
  4179. this.m[14] = z;
  4180. this._markAsUpdated();
  4181. return this;
  4182. };
  4183. /**
  4184. * Inserts the translation vector in the current Matrix.
  4185. * Returns the updated Matrix.
  4186. */
  4187. Matrix.prototype.setTranslation = function (vector3) {
  4188. this.m[12] = vector3.x;
  4189. this.m[13] = vector3.y;
  4190. this.m[14] = vector3.z;
  4191. this._markAsUpdated();
  4192. return this;
  4193. };
  4194. /**
  4195. * Returns a new Vector3 as the extracted translation from the Matrix.
  4196. */
  4197. Matrix.prototype.getTranslation = function () {
  4198. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4199. };
  4200. /**
  4201. * Fill a Vector3 with the extracted translation from the Matrix.
  4202. */
  4203. Matrix.prototype.getTranslationToRef = function (result) {
  4204. result.x = this.m[12];
  4205. result.y = this.m[13];
  4206. result.z = this.m[14];
  4207. return this;
  4208. };
  4209. /**
  4210. * Remove rotation and scaling part from the Matrix.
  4211. * Returns the updated Matrix.
  4212. */
  4213. Matrix.prototype.removeRotationAndScaling = function () {
  4214. this.setRowFromFloats(0, 1, 0, 0, 0);
  4215. this.setRowFromFloats(1, 0, 1, 0, 0);
  4216. this.setRowFromFloats(2, 0, 0, 1, 0);
  4217. return this;
  4218. };
  4219. /**
  4220. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4221. */
  4222. Matrix.prototype.multiply = function (other) {
  4223. var result = new Matrix();
  4224. this.multiplyToRef(other, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Updates the current Matrix from the passed one values.
  4229. * Returns the updated Matrix.
  4230. */
  4231. Matrix.prototype.copyFrom = function (other) {
  4232. for (var index = 0; index < 16; index++) {
  4233. this.m[index] = other.m[index];
  4234. }
  4235. this._markAsUpdated();
  4236. return this;
  4237. };
  4238. /**
  4239. * Populates the passed array from the starting index with the Matrix values.
  4240. * Returns the Matrix.
  4241. */
  4242. Matrix.prototype.copyToArray = function (array, offset) {
  4243. if (offset === void 0) { offset = 0; }
  4244. for (var index = 0; index < 16; index++) {
  4245. array[offset + index] = this.m[index];
  4246. }
  4247. return this;
  4248. };
  4249. /**
  4250. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4251. */
  4252. Matrix.prototype.multiplyToRef = function (other, result) {
  4253. this.multiplyToArray(other, result.m, 0);
  4254. result._markAsUpdated();
  4255. return this;
  4256. };
  4257. /**
  4258. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4259. */
  4260. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4261. var tm0 = this.m[0];
  4262. var tm1 = this.m[1];
  4263. var tm2 = this.m[2];
  4264. var tm3 = this.m[3];
  4265. var tm4 = this.m[4];
  4266. var tm5 = this.m[5];
  4267. var tm6 = this.m[6];
  4268. var tm7 = this.m[7];
  4269. var tm8 = this.m[8];
  4270. var tm9 = this.m[9];
  4271. var tm10 = this.m[10];
  4272. var tm11 = this.m[11];
  4273. var tm12 = this.m[12];
  4274. var tm13 = this.m[13];
  4275. var tm14 = this.m[14];
  4276. var tm15 = this.m[15];
  4277. var om0 = other.m[0];
  4278. var om1 = other.m[1];
  4279. var om2 = other.m[2];
  4280. var om3 = other.m[3];
  4281. var om4 = other.m[4];
  4282. var om5 = other.m[5];
  4283. var om6 = other.m[6];
  4284. var om7 = other.m[7];
  4285. var om8 = other.m[8];
  4286. var om9 = other.m[9];
  4287. var om10 = other.m[10];
  4288. var om11 = other.m[11];
  4289. var om12 = other.m[12];
  4290. var om13 = other.m[13];
  4291. var om14 = other.m[14];
  4292. var om15 = other.m[15];
  4293. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4294. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4295. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4296. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4297. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4298. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4299. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4300. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4301. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4302. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4303. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4304. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4305. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4306. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4307. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4308. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4309. return this;
  4310. };
  4311. /**
  4312. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4313. */
  4314. Matrix.prototype.equals = function (value) {
  4315. return value &&
  4316. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4317. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4318. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4319. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4320. };
  4321. /**
  4322. * Returns a new Matrix from the current Matrix.
  4323. */
  4324. Matrix.prototype.clone = function () {
  4325. 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]);
  4326. };
  4327. /**
  4328. * Returns the string "Matrix"
  4329. */
  4330. Matrix.prototype.getClassName = function () {
  4331. return "Matrix";
  4332. };
  4333. /**
  4334. * Returns the Matrix hash code.
  4335. */
  4336. Matrix.prototype.getHashCode = function () {
  4337. var hash = this.m[0] || 0;
  4338. for (var i = 1; i < 16; i++) {
  4339. hash = (hash * 397) ^ (this.m[i] || 0);
  4340. }
  4341. return hash;
  4342. };
  4343. /**
  4344. * Decomposes the current Matrix into :
  4345. * - a scale vector3 passed as a reference to update,
  4346. * - a rotation quaternion passed as a reference to update,
  4347. * - a translation vector3 passed as a reference to update.
  4348. * Returns the true if operation was successful.
  4349. */
  4350. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4351. translation.x = this.m[12];
  4352. translation.y = this.m[13];
  4353. translation.z = this.m[14];
  4354. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4355. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4356. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4357. if (this.determinant() <= 0) {
  4358. scale.y *= -1;
  4359. }
  4360. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4361. rotation.x = 0;
  4362. rotation.y = 0;
  4363. rotation.z = 0;
  4364. rotation.w = 1;
  4365. return false;
  4366. }
  4367. 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]);
  4368. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4369. return true;
  4370. };
  4371. /**
  4372. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4373. */
  4374. Matrix.prototype.getRotationMatrix = function () {
  4375. var result = Matrix.Identity();
  4376. this.getRotationMatrixToRef(result);
  4377. return result;
  4378. };
  4379. /**
  4380. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4381. * Returns the current Matrix.
  4382. */
  4383. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4384. var m = this.m;
  4385. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4386. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4387. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4388. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4389. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4390. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4391. 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);
  4392. return this;
  4393. };
  4394. // Statics
  4395. /**
  4396. * Returns a new Matrix set from the starting index of the passed array.
  4397. */
  4398. Matrix.FromArray = function (array, offset) {
  4399. var result = new Matrix();
  4400. if (!offset) {
  4401. offset = 0;
  4402. }
  4403. Matrix.FromArrayToRef(array, offset, result);
  4404. return result;
  4405. };
  4406. /**
  4407. * Sets the passed "result" matrix from the starting index of the passed array.
  4408. */
  4409. Matrix.FromArrayToRef = function (array, offset, result) {
  4410. for (var index = 0; index < 16; index++) {
  4411. result.m[index] = array[index + offset];
  4412. }
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4417. */
  4418. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4419. for (var index = 0; index < 16; index++) {
  4420. result.m[index] = array[index + offset] * scale;
  4421. }
  4422. result._markAsUpdated();
  4423. };
  4424. /**
  4425. * Sets the passed matrix "result" with the 16 passed floats.
  4426. */
  4427. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4428. result.m[0] = initialM11;
  4429. result.m[1] = initialM12;
  4430. result.m[2] = initialM13;
  4431. result.m[3] = initialM14;
  4432. result.m[4] = initialM21;
  4433. result.m[5] = initialM22;
  4434. result.m[6] = initialM23;
  4435. result.m[7] = initialM24;
  4436. result.m[8] = initialM31;
  4437. result.m[9] = initialM32;
  4438. result.m[10] = initialM33;
  4439. result.m[11] = initialM34;
  4440. result.m[12] = initialM41;
  4441. result.m[13] = initialM42;
  4442. result.m[14] = initialM43;
  4443. result.m[15] = initialM44;
  4444. result._markAsUpdated();
  4445. };
  4446. /**
  4447. * Returns the index-th row of the current matrix as a new Vector4.
  4448. */
  4449. Matrix.prototype.getRow = function (index) {
  4450. if (index < 0 || index > 3) {
  4451. return null;
  4452. }
  4453. var i = index * 4;
  4454. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4455. };
  4456. /**
  4457. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4458. * Returns the updated Matrix.
  4459. */
  4460. Matrix.prototype.setRow = function (index, row) {
  4461. if (index < 0 || index > 3) {
  4462. return this;
  4463. }
  4464. var i = index * 4;
  4465. this.m[i + 0] = row.x;
  4466. this.m[i + 1] = row.y;
  4467. this.m[i + 2] = row.z;
  4468. this.m[i + 3] = row.w;
  4469. this._markAsUpdated();
  4470. return this;
  4471. };
  4472. /**
  4473. * Compute the transpose of the matrix.
  4474. * Returns a new Matrix.
  4475. */
  4476. Matrix.prototype.transpose = function () {
  4477. return Matrix.Transpose(this);
  4478. };
  4479. /**
  4480. * Compute the transpose of the matrix.
  4481. * Returns the current matrix.
  4482. */
  4483. Matrix.prototype.transposeToRef = function (result) {
  4484. Matrix.TransposeToRef(this, result);
  4485. return this;
  4486. };
  4487. /**
  4488. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4489. * Returns the updated Matrix.
  4490. */
  4491. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4492. if (index < 0 || index > 3) {
  4493. return this;
  4494. }
  4495. var i = index * 4;
  4496. this.m[i + 0] = x;
  4497. this.m[i + 1] = y;
  4498. this.m[i + 2] = z;
  4499. this.m[i + 3] = w;
  4500. this._markAsUpdated();
  4501. return this;
  4502. };
  4503. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4504. /**
  4505. * Static identity matrix to be used as readonly matrix
  4506. * Must not be updated.
  4507. */
  4508. get: function () {
  4509. return Matrix._identityReadOnly;
  4510. },
  4511. enumerable: true,
  4512. configurable: true
  4513. });
  4514. /**
  4515. * Returns a new Matrix set from the 16 passed floats.
  4516. */
  4517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4518. var result = new Matrix();
  4519. result.m[0] = initialM11;
  4520. result.m[1] = initialM12;
  4521. result.m[2] = initialM13;
  4522. result.m[3] = initialM14;
  4523. result.m[4] = initialM21;
  4524. result.m[5] = initialM22;
  4525. result.m[6] = initialM23;
  4526. result.m[7] = initialM24;
  4527. result.m[8] = initialM31;
  4528. result.m[9] = initialM32;
  4529. result.m[10] = initialM33;
  4530. result.m[11] = initialM34;
  4531. result.m[12] = initialM41;
  4532. result.m[13] = initialM42;
  4533. result.m[14] = initialM43;
  4534. result.m[15] = initialM44;
  4535. return result;
  4536. };
  4537. /**
  4538. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4539. */
  4540. Matrix.Compose = function (scale, rotation, translation) {
  4541. var result = Matrix.Identity();
  4542. Matrix.ComposeToRef(scale, rotation, translation, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4547. */
  4548. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4549. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4550. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4551. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4552. result.setTranslation(translation);
  4553. };
  4554. /**
  4555. * Returns a new indentity Matrix.
  4556. */
  4557. Matrix.Identity = function () {
  4558. 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);
  4559. };
  4560. /**
  4561. * Sets the passed "result" as an identity matrix.
  4562. */
  4563. Matrix.IdentityToRef = function (result) {
  4564. 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);
  4565. };
  4566. /**
  4567. * Returns a new zero Matrix.
  4568. */
  4569. Matrix.Zero = function () {
  4570. 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);
  4571. };
  4572. /**
  4573. * Returns a new rotation matrix for "angle" radians around the X axis.
  4574. */
  4575. Matrix.RotationX = function (angle) {
  4576. var result = new Matrix();
  4577. Matrix.RotationXToRef(angle, result);
  4578. return result;
  4579. };
  4580. /**
  4581. * Returns a new Matrix as the passed inverted one.
  4582. */
  4583. Matrix.Invert = function (source) {
  4584. var result = new Matrix();
  4585. source.invertToRef(result);
  4586. return result;
  4587. };
  4588. /**
  4589. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4590. */
  4591. Matrix.RotationXToRef = function (angle, result) {
  4592. var s = Math.sin(angle);
  4593. var c = Math.cos(angle);
  4594. result.m[0] = 1.0;
  4595. result.m[15] = 1.0;
  4596. result.m[5] = c;
  4597. result.m[10] = c;
  4598. result.m[9] = -s;
  4599. result.m[6] = s;
  4600. result.m[1] = 0.0;
  4601. result.m[2] = 0.0;
  4602. result.m[3] = 0.0;
  4603. result.m[4] = 0.0;
  4604. result.m[7] = 0.0;
  4605. result.m[8] = 0.0;
  4606. result.m[11] = 0.0;
  4607. result.m[12] = 0.0;
  4608. result.m[13] = 0.0;
  4609. result.m[14] = 0.0;
  4610. result._markAsUpdated();
  4611. };
  4612. /**
  4613. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4614. */
  4615. Matrix.RotationY = function (angle) {
  4616. var result = new Matrix();
  4617. Matrix.RotationYToRef(angle, result);
  4618. return result;
  4619. };
  4620. /**
  4621. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4622. */
  4623. Matrix.RotationYToRef = function (angle, result) {
  4624. var s = Math.sin(angle);
  4625. var c = Math.cos(angle);
  4626. result.m[5] = 1.0;
  4627. result.m[15] = 1.0;
  4628. result.m[0] = c;
  4629. result.m[2] = -s;
  4630. result.m[8] = s;
  4631. result.m[10] = c;
  4632. result.m[1] = 0.0;
  4633. result.m[3] = 0.0;
  4634. result.m[4] = 0.0;
  4635. result.m[6] = 0.0;
  4636. result.m[7] = 0.0;
  4637. result.m[9] = 0.0;
  4638. result.m[11] = 0.0;
  4639. result.m[12] = 0.0;
  4640. result.m[13] = 0.0;
  4641. result.m[14] = 0.0;
  4642. result._markAsUpdated();
  4643. };
  4644. /**
  4645. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4646. */
  4647. Matrix.RotationZ = function (angle) {
  4648. var result = new Matrix();
  4649. Matrix.RotationZToRef(angle, result);
  4650. return result;
  4651. };
  4652. /**
  4653. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4654. */
  4655. Matrix.RotationZToRef = function (angle, result) {
  4656. var s = Math.sin(angle);
  4657. var c = Math.cos(angle);
  4658. result.m[10] = 1.0;
  4659. result.m[15] = 1.0;
  4660. result.m[0] = c;
  4661. result.m[1] = s;
  4662. result.m[4] = -s;
  4663. result.m[5] = c;
  4664. result.m[2] = 0.0;
  4665. result.m[3] = 0.0;
  4666. result.m[6] = 0.0;
  4667. result.m[7] = 0.0;
  4668. result.m[8] = 0.0;
  4669. result.m[9] = 0.0;
  4670. result.m[11] = 0.0;
  4671. result.m[12] = 0.0;
  4672. result.m[13] = 0.0;
  4673. result.m[14] = 0.0;
  4674. result._markAsUpdated();
  4675. };
  4676. /**
  4677. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4678. */
  4679. Matrix.RotationAxis = function (axis, angle) {
  4680. var result = Matrix.Zero();
  4681. Matrix.RotationAxisToRef(axis, angle, result);
  4682. return result;
  4683. };
  4684. /**
  4685. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4686. */
  4687. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4688. var s = Math.sin(-angle);
  4689. var c = Math.cos(-angle);
  4690. var c1 = 1 - c;
  4691. axis.normalize();
  4692. result.m[0] = (axis.x * axis.x) * c1 + c;
  4693. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4694. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4695. result.m[3] = 0.0;
  4696. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4697. result.m[5] = (axis.y * axis.y) * c1 + c;
  4698. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4699. result.m[7] = 0.0;
  4700. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4701. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4702. result.m[10] = (axis.z * axis.z) * c1 + c;
  4703. result.m[11] = 0.0;
  4704. result.m[15] = 1.0;
  4705. result._markAsUpdated();
  4706. };
  4707. /**
  4708. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4709. */
  4710. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4711. var result = new Matrix();
  4712. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4713. return result;
  4714. };
  4715. /**
  4716. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4717. */
  4718. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4719. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4720. this._tempQuaternion.toRotationMatrix(result);
  4721. };
  4722. /**
  4723. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4724. */
  4725. Matrix.Scaling = function (x, y, z) {
  4726. var result = Matrix.Zero();
  4727. Matrix.ScalingToRef(x, y, z, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4732. */
  4733. Matrix.ScalingToRef = function (x, y, z, result) {
  4734. result.m[0] = x;
  4735. result.m[1] = 0.0;
  4736. result.m[2] = 0.0;
  4737. result.m[3] = 0.0;
  4738. result.m[4] = 0.0;
  4739. result.m[5] = y;
  4740. result.m[6] = 0.0;
  4741. result.m[7] = 0.0;
  4742. result.m[8] = 0.0;
  4743. result.m[9] = 0.0;
  4744. result.m[10] = z;
  4745. result.m[11] = 0.0;
  4746. result.m[12] = 0.0;
  4747. result.m[13] = 0.0;
  4748. result.m[14] = 0.0;
  4749. result.m[15] = 1.0;
  4750. result._markAsUpdated();
  4751. };
  4752. /**
  4753. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4754. */
  4755. Matrix.Translation = function (x, y, z) {
  4756. var result = Matrix.Identity();
  4757. Matrix.TranslationToRef(x, y, z, result);
  4758. return result;
  4759. };
  4760. /**
  4761. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4762. */
  4763. Matrix.TranslationToRef = function (x, y, z, result) {
  4764. 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);
  4765. };
  4766. /**
  4767. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4768. */
  4769. Matrix.Lerp = function (startValue, endValue, gradient) {
  4770. var result = Matrix.Zero();
  4771. for (var index = 0; index < 16; index++) {
  4772. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4773. }
  4774. result._markAsUpdated();
  4775. return result;
  4776. };
  4777. /**
  4778. * Returns a new Matrix whose values are computed by :
  4779. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4780. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4781. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4782. */
  4783. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4784. var startScale = new Vector3(0, 0, 0);
  4785. var startRotation = new Quaternion();
  4786. var startTranslation = new Vector3(0, 0, 0);
  4787. startValue.decompose(startScale, startRotation, startTranslation);
  4788. var endScale = new Vector3(0, 0, 0);
  4789. var endRotation = new Quaternion();
  4790. var endTranslation = new Vector3(0, 0, 0);
  4791. endValue.decompose(endScale, endRotation, endTranslation);
  4792. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4793. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4794. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4795. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4796. };
  4797. /**
  4798. * 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".
  4799. * This methods works for a Left-Handed system.
  4800. */
  4801. Matrix.LookAtLH = function (eye, target, up) {
  4802. var result = Matrix.Zero();
  4803. Matrix.LookAtLHToRef(eye, target, up, result);
  4804. return result;
  4805. };
  4806. /**
  4807. * 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".
  4808. * This methods works for a Left-Handed system.
  4809. */
  4810. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4811. // Z axis
  4812. target.subtractToRef(eye, this._zAxis);
  4813. this._zAxis.normalize();
  4814. // X axis
  4815. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4816. if (this._xAxis.lengthSquared() === 0) {
  4817. this._xAxis.x = 1.0;
  4818. }
  4819. else {
  4820. this._xAxis.normalize();
  4821. }
  4822. // Y axis
  4823. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4824. this._yAxis.normalize();
  4825. // Eye angles
  4826. var ex = -Vector3.Dot(this._xAxis, eye);
  4827. var ey = -Vector3.Dot(this._yAxis, eye);
  4828. var ez = -Vector3.Dot(this._zAxis, eye);
  4829. 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);
  4830. };
  4831. /**
  4832. * 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".
  4833. * This methods works for a Right-Handed system.
  4834. */
  4835. Matrix.LookAtRH = function (eye, target, up) {
  4836. var result = Matrix.Zero();
  4837. Matrix.LookAtRHToRef(eye, target, up, result);
  4838. return result;
  4839. };
  4840. /**
  4841. * 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".
  4842. * This methods works for a Left-Handed system.
  4843. */
  4844. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4845. // Z axis
  4846. eye.subtractToRef(target, this._zAxis);
  4847. this._zAxis.normalize();
  4848. // X axis
  4849. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4850. if (this._xAxis.lengthSquared() === 0) {
  4851. this._xAxis.x = 1.0;
  4852. }
  4853. else {
  4854. this._xAxis.normalize();
  4855. }
  4856. // Y axis
  4857. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4858. this._yAxis.normalize();
  4859. // Eye angles
  4860. var ex = -Vector3.Dot(this._xAxis, eye);
  4861. var ey = -Vector3.Dot(this._yAxis, eye);
  4862. var ez = -Vector3.Dot(this._zAxis, eye);
  4863. 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);
  4864. };
  4865. /**
  4866. * 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.
  4867. */
  4868. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4869. var matrix = Matrix.Zero();
  4870. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4871. return matrix;
  4872. };
  4873. /**
  4874. * 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.
  4875. */
  4876. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4877. var n = znear;
  4878. var f = zfar;
  4879. var a = 2.0 / width;
  4880. var b = 2.0 / height;
  4881. var c = 2.0 / (f - n);
  4882. var d = -(f + n) / (f - n);
  4883. 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);
  4884. };
  4885. /**
  4886. * 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.
  4887. */
  4888. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4889. var matrix = Matrix.Zero();
  4890. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4891. return matrix;
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4897. var n = znear;
  4898. var f = zfar;
  4899. var a = 2.0 / (right - left);
  4900. var b = 2.0 / (top - bottom);
  4901. var c = 2.0 / (f - n);
  4902. var d = -(f + n) / (f - n);
  4903. var i0 = (left + right) / (left - right);
  4904. var i1 = (top + bottom) / (bottom - top);
  4905. 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);
  4906. };
  4907. /**
  4908. * 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.
  4909. */
  4910. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4911. var matrix = Matrix.Zero();
  4912. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4913. return matrix;
  4914. };
  4915. /**
  4916. * 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.
  4917. */
  4918. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4919. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4920. result.m[10] *= -1.0;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. var n = znear;
  4928. var f = zfar;
  4929. var a = 2.0 * n / width;
  4930. var b = 2.0 * n / height;
  4931. var c = (f + n) / (f - n);
  4932. var d = -2.0 * f * n / (f - n);
  4933. 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);
  4934. return matrix;
  4935. };
  4936. /**
  4937. * 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.
  4938. */
  4939. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4940. var matrix = Matrix.Zero();
  4941. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4942. return matrix;
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4948. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4949. var n = znear;
  4950. var f = zfar;
  4951. var t = 1.0 / (Math.tan(fov * 0.5));
  4952. var a = isVerticalFovFixed ? (t / aspect) : t;
  4953. var b = isVerticalFovFixed ? t : (t * aspect);
  4954. var c = (f + n) / (f - n);
  4955. var d = -2.0 * f * n / (f - n);
  4956. 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);
  4957. };
  4958. /**
  4959. * 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.
  4960. */
  4961. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4962. var matrix = Matrix.Zero();
  4963. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4964. return matrix;
  4965. };
  4966. /**
  4967. * 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.
  4968. */
  4969. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4970. //alternatively this could be expressed as:
  4971. // m = PerspectiveFovLHToRef
  4972. // m[10] *= -1.0;
  4973. // m[11] *= -1.0;
  4974. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4975. var n = znear;
  4976. var f = zfar;
  4977. var t = 1.0 / (Math.tan(fov * 0.5));
  4978. var a = isVerticalFovFixed ? (t / aspect) : t;
  4979. var b = isVerticalFovFixed ? t : (t * aspect);
  4980. var c = -(f + n) / (f - n);
  4981. var d = -2 * f * n / (f - n);
  4982. 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);
  4983. };
  4984. /**
  4985. * 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.
  4986. */
  4987. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4988. if (rightHanded === void 0) { rightHanded = false; }
  4989. var rightHandedFactor = rightHanded ? -1 : 1;
  4990. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4991. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4992. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4993. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4994. var xScale = 2.0 / (leftTan + rightTan);
  4995. var yScale = 2.0 / (upTan + downTan);
  4996. result.m[0] = xScale;
  4997. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4998. result.m[5] = yScale;
  4999. result.m[6] = result.m[7] = 0.0;
  5000. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5001. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5002. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5003. result.m[10] = -zfar / (znear - zfar);
  5004. result.m[11] = 1.0 * rightHandedFactor;
  5005. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5006. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5007. // result.m[14] = (znear * zfar) / (znear - zfar);
  5008. result._markAsUpdated();
  5009. };
  5010. /**
  5011. * Returns the final transformation matrix : world * view * projection * viewport
  5012. */
  5013. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5014. var cw = viewport.width;
  5015. var ch = viewport.height;
  5016. var cx = viewport.x;
  5017. var cy = viewport.y;
  5018. 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);
  5019. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5020. };
  5021. /**
  5022. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5023. */
  5024. Matrix.GetAsMatrix2x2 = function (matrix) {
  5025. return new Float32Array([
  5026. matrix.m[0], matrix.m[1],
  5027. matrix.m[4], matrix.m[5]
  5028. ]);
  5029. };
  5030. /**
  5031. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5032. */
  5033. Matrix.GetAsMatrix3x3 = function (matrix) {
  5034. return new Float32Array([
  5035. matrix.m[0], matrix.m[1], matrix.m[2],
  5036. matrix.m[4], matrix.m[5], matrix.m[6],
  5037. matrix.m[8], matrix.m[9], matrix.m[10]
  5038. ]);
  5039. };
  5040. /**
  5041. * Compute the transpose of the passed Matrix.
  5042. * Returns a new Matrix.
  5043. */
  5044. Matrix.Transpose = function (matrix) {
  5045. var result = new Matrix();
  5046. Matrix.TransposeToRef(matrix, result);
  5047. return result;
  5048. };
  5049. /**
  5050. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5051. */
  5052. Matrix.TransposeToRef = function (matrix, result) {
  5053. result.m[0] = matrix.m[0];
  5054. result.m[1] = matrix.m[4];
  5055. result.m[2] = matrix.m[8];
  5056. result.m[3] = matrix.m[12];
  5057. result.m[4] = matrix.m[1];
  5058. result.m[5] = matrix.m[5];
  5059. result.m[6] = matrix.m[9];
  5060. result.m[7] = matrix.m[13];
  5061. result.m[8] = matrix.m[2];
  5062. result.m[9] = matrix.m[6];
  5063. result.m[10] = matrix.m[10];
  5064. result.m[11] = matrix.m[14];
  5065. result.m[12] = matrix.m[3];
  5066. result.m[13] = matrix.m[7];
  5067. result.m[14] = matrix.m[11];
  5068. result.m[15] = matrix.m[15];
  5069. };
  5070. /**
  5071. * Returns a new Matrix as the reflection matrix across the passed plane.
  5072. */
  5073. Matrix.Reflection = function (plane) {
  5074. var matrix = new Matrix();
  5075. Matrix.ReflectionToRef(plane, matrix);
  5076. return matrix;
  5077. };
  5078. /**
  5079. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5080. */
  5081. Matrix.ReflectionToRef = function (plane, result) {
  5082. plane.normalize();
  5083. var x = plane.normal.x;
  5084. var y = plane.normal.y;
  5085. var z = plane.normal.z;
  5086. var temp = -2 * x;
  5087. var temp2 = -2 * y;
  5088. var temp3 = -2 * z;
  5089. result.m[0] = (temp * x) + 1;
  5090. result.m[1] = temp2 * x;
  5091. result.m[2] = temp3 * x;
  5092. result.m[3] = 0.0;
  5093. result.m[4] = temp * y;
  5094. result.m[5] = (temp2 * y) + 1;
  5095. result.m[6] = temp3 * y;
  5096. result.m[7] = 0.0;
  5097. result.m[8] = temp * z;
  5098. result.m[9] = temp2 * z;
  5099. result.m[10] = (temp3 * z) + 1;
  5100. result.m[11] = 0.0;
  5101. result.m[12] = temp * plane.d;
  5102. result.m[13] = temp2 * plane.d;
  5103. result.m[14] = temp3 * plane.d;
  5104. result.m[15] = 1.0;
  5105. result._markAsUpdated();
  5106. };
  5107. /**
  5108. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5109. */
  5110. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5111. result.m[0] = xaxis.x;
  5112. result.m[1] = xaxis.y;
  5113. result.m[2] = xaxis.z;
  5114. result.m[3] = 0.0;
  5115. result.m[4] = yaxis.x;
  5116. result.m[5] = yaxis.y;
  5117. result.m[6] = yaxis.z;
  5118. result.m[7] = 0.0;
  5119. result.m[8] = zaxis.x;
  5120. result.m[9] = zaxis.y;
  5121. result.m[10] = zaxis.z;
  5122. result.m[11] = 0.0;
  5123. result.m[12] = 0.0;
  5124. result.m[13] = 0.0;
  5125. result.m[14] = 0.0;
  5126. result.m[15] = 1.0;
  5127. result._markAsUpdated();
  5128. };
  5129. /**
  5130. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5131. */
  5132. Matrix.FromQuaternionToRef = function (quat, result) {
  5133. var xx = quat.x * quat.x;
  5134. var yy = quat.y * quat.y;
  5135. var zz = quat.z * quat.z;
  5136. var xy = quat.x * quat.y;
  5137. var zw = quat.z * quat.w;
  5138. var zx = quat.z * quat.x;
  5139. var yw = quat.y * quat.w;
  5140. var yz = quat.y * quat.z;
  5141. var xw = quat.x * quat.w;
  5142. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5143. result.m[1] = 2.0 * (xy + zw);
  5144. result.m[2] = 2.0 * (zx - yw);
  5145. result.m[3] = 0.0;
  5146. result.m[4] = 2.0 * (xy - zw);
  5147. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5148. result.m[6] = 2.0 * (yz + xw);
  5149. result.m[7] = 0.0;
  5150. result.m[8] = 2.0 * (zx + yw);
  5151. result.m[9] = 2.0 * (yz - xw);
  5152. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5153. result.m[11] = 0.0;
  5154. result.m[12] = 0.0;
  5155. result.m[13] = 0.0;
  5156. result.m[14] = 0.0;
  5157. result.m[15] = 1.0;
  5158. result._markAsUpdated();
  5159. };
  5160. Matrix._tempQuaternion = new Quaternion();
  5161. Matrix._xAxis = Vector3.Zero();
  5162. Matrix._yAxis = Vector3.Zero();
  5163. Matrix._zAxis = Vector3.Zero();
  5164. Matrix._updateFlagSeed = 0;
  5165. Matrix._identityReadOnly = Matrix.Identity();
  5166. return Matrix;
  5167. }());
  5168. BABYLON.Matrix = Matrix;
  5169. var Plane = /** @class */ (function () {
  5170. /**
  5171. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5172. */
  5173. function Plane(a, b, c, d) {
  5174. this.normal = new Vector3(a, b, c);
  5175. this.d = d;
  5176. }
  5177. /**
  5178. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5179. */
  5180. Plane.prototype.asArray = function () {
  5181. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5182. };
  5183. // Methods
  5184. /**
  5185. * Returns a new plane copied from the current Plane.
  5186. */
  5187. Plane.prototype.clone = function () {
  5188. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5189. };
  5190. /**
  5191. * Returns the string "Plane".
  5192. */
  5193. Plane.prototype.getClassName = function () {
  5194. return "Plane";
  5195. };
  5196. /**
  5197. * Returns the Plane hash code.
  5198. */
  5199. Plane.prototype.getHashCode = function () {
  5200. var hash = this.normal.getHashCode();
  5201. hash = (hash * 397) ^ (this.d || 0);
  5202. return hash;
  5203. };
  5204. /**
  5205. * Normalize the current Plane in place.
  5206. * Returns the updated Plane.
  5207. */
  5208. Plane.prototype.normalize = function () {
  5209. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5210. var magnitude = 0.0;
  5211. if (norm !== 0) {
  5212. magnitude = 1.0 / norm;
  5213. }
  5214. this.normal.x *= magnitude;
  5215. this.normal.y *= magnitude;
  5216. this.normal.z *= magnitude;
  5217. this.d *= magnitude;
  5218. return this;
  5219. };
  5220. /**
  5221. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5222. */
  5223. Plane.prototype.transform = function (transformation) {
  5224. var transposedMatrix = Matrix.Transpose(transformation);
  5225. var x = this.normal.x;
  5226. var y = this.normal.y;
  5227. var z = this.normal.z;
  5228. var d = this.d;
  5229. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5230. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5231. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5232. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5233. return new Plane(normalX, normalY, normalZ, finalD);
  5234. };
  5235. /**
  5236. * Returns the dot product (float) of the point coordinates and the plane normal.
  5237. */
  5238. Plane.prototype.dotCoordinate = function (point) {
  5239. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5240. };
  5241. /**
  5242. * Updates the current Plane from the plane defined by the three passed points.
  5243. * Returns the updated Plane.
  5244. */
  5245. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5246. var x1 = point2.x - point1.x;
  5247. var y1 = point2.y - point1.y;
  5248. var z1 = point2.z - point1.z;
  5249. var x2 = point3.x - point1.x;
  5250. var y2 = point3.y - point1.y;
  5251. var z2 = point3.z - point1.z;
  5252. var yz = (y1 * z2) - (z1 * y2);
  5253. var xz = (z1 * x2) - (x1 * z2);
  5254. var xy = (x1 * y2) - (y1 * x2);
  5255. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5256. var invPyth;
  5257. if (pyth !== 0) {
  5258. invPyth = 1.0 / pyth;
  5259. }
  5260. else {
  5261. invPyth = 0.0;
  5262. }
  5263. this.normal.x = yz * invPyth;
  5264. this.normal.y = xz * invPyth;
  5265. this.normal.z = xy * invPyth;
  5266. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5267. return this;
  5268. };
  5269. /**
  5270. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5271. */
  5272. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5273. var dot = Vector3.Dot(this.normal, direction);
  5274. return (dot <= epsilon);
  5275. };
  5276. /**
  5277. * Returns the signed distance (float) from the passed point to the Plane.
  5278. */
  5279. Plane.prototype.signedDistanceTo = function (point) {
  5280. return Vector3.Dot(point, this.normal) + this.d;
  5281. };
  5282. // Statics
  5283. /**
  5284. * Returns a new Plane from the passed array.
  5285. */
  5286. Plane.FromArray = function (array) {
  5287. return new Plane(array[0], array[1], array[2], array[3]);
  5288. };
  5289. /**
  5290. * Returns a new Plane defined by the three passed points.
  5291. */
  5292. Plane.FromPoints = function (point1, point2, point3) {
  5293. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5294. result.copyFromPoints(point1, point2, point3);
  5295. return result;
  5296. };
  5297. /**
  5298. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5299. * Note : the vector "normal" is updated because normalized.
  5300. */
  5301. Plane.FromPositionAndNormal = function (origin, normal) {
  5302. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5303. normal.normalize();
  5304. result.normal = normal;
  5305. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5306. return result;
  5307. };
  5308. /**
  5309. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5310. */
  5311. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5312. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5313. return Vector3.Dot(point, normal) + d;
  5314. };
  5315. return Plane;
  5316. }());
  5317. BABYLON.Plane = Plane;
  5318. var Viewport = /** @class */ (function () {
  5319. /**
  5320. * Creates a Viewport object located at (x, y) and sized (width, height).
  5321. */
  5322. function Viewport(x, y, width, height) {
  5323. this.x = x;
  5324. this.y = y;
  5325. this.width = width;
  5326. this.height = height;
  5327. }
  5328. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5329. if (renderWidthOrEngine.getRenderWidth) {
  5330. var engine = renderWidthOrEngine;
  5331. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5332. }
  5333. var renderWidth = renderWidthOrEngine;
  5334. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5335. };
  5336. /**
  5337. * Returns a new Viewport copied from the current one.
  5338. */
  5339. Viewport.prototype.clone = function () {
  5340. return new Viewport(this.x, this.y, this.width, this.height);
  5341. };
  5342. return Viewport;
  5343. }());
  5344. BABYLON.Viewport = Viewport;
  5345. var Frustum = /** @class */ (function () {
  5346. function Frustum() {
  5347. }
  5348. /**
  5349. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5350. */
  5351. Frustum.GetPlanes = function (transform) {
  5352. var frustumPlanes = [];
  5353. for (var index = 0; index < 6; index++) {
  5354. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5355. }
  5356. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5357. return frustumPlanes;
  5358. };
  5359. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5363. frustumPlane.d = transform.m[15] + transform.m[14];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5370. frustumPlane.d = transform.m[15] - transform.m[14];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5375. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5376. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5377. frustumPlane.d = transform.m[15] + transform.m[12];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5382. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5383. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5384. frustumPlane.d = transform.m[15] - transform.m[12];
  5385. frustumPlane.normalize();
  5386. };
  5387. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5388. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5389. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5390. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5391. frustumPlane.d = transform.m[15] - transform.m[13];
  5392. frustumPlane.normalize();
  5393. };
  5394. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5395. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5396. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5397. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5398. frustumPlane.d = transform.m[15] + transform.m[13];
  5399. frustumPlane.normalize();
  5400. };
  5401. /**
  5402. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5403. */
  5404. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5405. // Near
  5406. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5407. // Far
  5408. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5409. // Left
  5410. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5411. // Right
  5412. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5413. // Top
  5414. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5415. // Bottom
  5416. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5417. };
  5418. return Frustum;
  5419. }());
  5420. BABYLON.Frustum = Frustum;
  5421. var Space;
  5422. (function (Space) {
  5423. Space[Space["LOCAL"] = 0] = "LOCAL";
  5424. Space[Space["WORLD"] = 1] = "WORLD";
  5425. Space[Space["BONE"] = 2] = "BONE";
  5426. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5427. var Axis = /** @class */ (function () {
  5428. function Axis() {
  5429. }
  5430. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5431. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5432. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5433. return Axis;
  5434. }());
  5435. BABYLON.Axis = Axis;
  5436. ;
  5437. var BezierCurve = /** @class */ (function () {
  5438. function BezierCurve() {
  5439. }
  5440. /**
  5441. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5442. */
  5443. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5444. // Extract X (which is equal to time here)
  5445. var f0 = 1 - 3 * x2 + 3 * x1;
  5446. var f1 = 3 * x2 - 6 * x1;
  5447. var f2 = 3 * x1;
  5448. var refinedT = t;
  5449. for (var i = 0; i < 5; i++) {
  5450. var refinedT2 = refinedT * refinedT;
  5451. var refinedT3 = refinedT2 * refinedT;
  5452. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5453. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5454. refinedT -= (x - t) * slope;
  5455. refinedT = Math.min(1, Math.max(0, refinedT));
  5456. }
  5457. // Resolve cubic bezier for the given x
  5458. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5459. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5460. Math.pow(refinedT, 3);
  5461. };
  5462. return BezierCurve;
  5463. }());
  5464. BABYLON.BezierCurve = BezierCurve;
  5465. var Orientation;
  5466. (function (Orientation) {
  5467. Orientation[Orientation["CW"] = 0] = "CW";
  5468. Orientation[Orientation["CCW"] = 1] = "CCW";
  5469. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5470. var Angle = /** @class */ (function () {
  5471. /**
  5472. * Creates an Angle object of "radians" radians (float).
  5473. */
  5474. function Angle(radians) {
  5475. var _this = this;
  5476. /**
  5477. * Returns the Angle value in degrees (float).
  5478. */
  5479. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5480. /**
  5481. * Returns the Angle value in radians (float).
  5482. */
  5483. this.radians = function () { return _this._radians; };
  5484. this._radians = radians;
  5485. if (this._radians < 0.0)
  5486. this._radians += (2.0 * Math.PI);
  5487. }
  5488. /**
  5489. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5490. */
  5491. Angle.BetweenTwoPoints = function (a, b) {
  5492. var delta = b.subtract(a);
  5493. var theta = Math.atan2(delta.y, delta.x);
  5494. return new Angle(theta);
  5495. };
  5496. /**
  5497. * Returns a new Angle object from the passed float in radians.
  5498. */
  5499. Angle.FromRadians = function (radians) {
  5500. return new Angle(radians);
  5501. };
  5502. /**
  5503. * Returns a new Angle object from the passed float in degrees.
  5504. */
  5505. Angle.FromDegrees = function (degrees) {
  5506. return new Angle(degrees * Math.PI / 180.0);
  5507. };
  5508. return Angle;
  5509. }());
  5510. BABYLON.Angle = Angle;
  5511. var Arc2 = /** @class */ (function () {
  5512. /**
  5513. * Creates an Arc object from the three passed points : start, middle and end.
  5514. */
  5515. function Arc2(startPoint, midPoint, endPoint) {
  5516. this.startPoint = startPoint;
  5517. this.midPoint = midPoint;
  5518. this.endPoint = endPoint;
  5519. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5520. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5521. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5522. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5523. 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);
  5524. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5525. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5526. var a1 = this.startAngle.degrees();
  5527. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5528. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5529. // angles correction
  5530. if (a2 - a1 > +180.0)
  5531. a2 -= 360.0;
  5532. if (a2 - a1 < -180.0)
  5533. a2 += 360.0;
  5534. if (a3 - a2 > +180.0)
  5535. a3 -= 360.0;
  5536. if (a3 - a2 < -180.0)
  5537. a3 += 360.0;
  5538. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5539. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5540. }
  5541. return Arc2;
  5542. }());
  5543. BABYLON.Arc2 = Arc2;
  5544. var Path2 = /** @class */ (function () {
  5545. /**
  5546. * Creates a Path2 object from the starting 2D coordinates x and y.
  5547. */
  5548. function Path2(x, y) {
  5549. this._points = new Array();
  5550. this._length = 0.0;
  5551. this.closed = false;
  5552. this._points.push(new Vector2(x, y));
  5553. }
  5554. /**
  5555. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5556. * Returns the updated Path2.
  5557. */
  5558. Path2.prototype.addLineTo = function (x, y) {
  5559. if (this.closed) {
  5560. //Tools.Error("cannot add lines to closed paths");
  5561. return this;
  5562. }
  5563. var newPoint = new Vector2(x, y);
  5564. var previousPoint = this._points[this._points.length - 1];
  5565. this._points.push(newPoint);
  5566. this._length += newPoint.subtract(previousPoint).length();
  5567. return this;
  5568. };
  5569. /**
  5570. * 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.
  5571. * Returns the updated Path2.
  5572. */
  5573. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5574. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5575. if (this.closed) {
  5576. //Tools.Error("cannot add arcs to closed paths");
  5577. return this;
  5578. }
  5579. var startPoint = this._points[this._points.length - 1];
  5580. var midPoint = new Vector2(midX, midY);
  5581. var endPoint = new Vector2(endX, endY);
  5582. var arc = new Arc2(startPoint, midPoint, endPoint);
  5583. var increment = arc.angle.radians() / numberOfSegments;
  5584. if (arc.orientation === Orientation.CW)
  5585. increment *= -1;
  5586. var currentAngle = arc.startAngle.radians() + increment;
  5587. for (var i = 0; i < numberOfSegments; i++) {
  5588. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5589. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5590. this.addLineTo(x, y);
  5591. currentAngle += increment;
  5592. }
  5593. return this;
  5594. };
  5595. /**
  5596. * Closes the Path2.
  5597. * Returns the Path2.
  5598. */
  5599. Path2.prototype.close = function () {
  5600. this.closed = true;
  5601. return this;
  5602. };
  5603. /**
  5604. * Returns the Path2 total length (float).
  5605. */
  5606. Path2.prototype.length = function () {
  5607. var result = this._length;
  5608. if (!this.closed) {
  5609. var lastPoint = this._points[this._points.length - 1];
  5610. var firstPoint = this._points[0];
  5611. result += (firstPoint.subtract(lastPoint).length());
  5612. }
  5613. return result;
  5614. };
  5615. /**
  5616. * Returns the Path2 internal array of points.
  5617. */
  5618. Path2.prototype.getPoints = function () {
  5619. return this._points;
  5620. };
  5621. /**
  5622. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5623. */
  5624. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5625. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5626. //Tools.Error("normalized length position should be between 0 and 1.");
  5627. return Vector2.Zero();
  5628. }
  5629. var lengthPosition = normalizedLengthPosition * this.length();
  5630. var previousOffset = 0;
  5631. for (var i = 0; i < this._points.length; i++) {
  5632. var j = (i + 1) % this._points.length;
  5633. var a = this._points[i];
  5634. var b = this._points[j];
  5635. var bToA = b.subtract(a);
  5636. var nextOffset = (bToA.length() + previousOffset);
  5637. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5638. var dir = bToA.normalize();
  5639. var localOffset = lengthPosition - previousOffset;
  5640. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5641. }
  5642. previousOffset = nextOffset;
  5643. }
  5644. //Tools.Error("internal error");
  5645. return Vector2.Zero();
  5646. };
  5647. /**
  5648. * Returns a new Path2 starting at the coordinates (x, y).
  5649. */
  5650. Path2.StartingAt = function (x, y) {
  5651. return new Path2(x, y);
  5652. };
  5653. return Path2;
  5654. }());
  5655. BABYLON.Path2 = Path2;
  5656. var Path3D = /** @class */ (function () {
  5657. /**
  5658. * new Path3D(path, normal, raw)
  5659. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5660. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5661. * path : an array of Vector3, the curve axis of the Path3D
  5662. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5663. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5664. */
  5665. function Path3D(path, firstNormal, raw) {
  5666. if (firstNormal === void 0) { firstNormal = null; }
  5667. this.path = path;
  5668. this._curve = new Array();
  5669. this._distances = new Array();
  5670. this._tangents = new Array();
  5671. this._normals = new Array();
  5672. this._binormals = new Array();
  5673. for (var p = 0; p < path.length; p++) {
  5674. this._curve[p] = path[p].clone(); // hard copy
  5675. }
  5676. this._raw = raw || false;
  5677. this._compute(firstNormal);
  5678. }
  5679. /**
  5680. * Returns the Path3D array of successive Vector3 designing its curve.
  5681. */
  5682. Path3D.prototype.getCurve = function () {
  5683. return this._curve;
  5684. };
  5685. /**
  5686. * Returns an array populated with tangent vectors on each Path3D curve point.
  5687. */
  5688. Path3D.prototype.getTangents = function () {
  5689. return this._tangents;
  5690. };
  5691. /**
  5692. * Returns an array populated with normal vectors on each Path3D curve point.
  5693. */
  5694. Path3D.prototype.getNormals = function () {
  5695. return this._normals;
  5696. };
  5697. /**
  5698. * Returns an array populated with binormal vectors on each Path3D curve point.
  5699. */
  5700. Path3D.prototype.getBinormals = function () {
  5701. return this._binormals;
  5702. };
  5703. /**
  5704. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5705. */
  5706. Path3D.prototype.getDistances = function () {
  5707. return this._distances;
  5708. };
  5709. /**
  5710. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5711. * Returns the same object updated.
  5712. */
  5713. Path3D.prototype.update = function (path, firstNormal) {
  5714. if (firstNormal === void 0) { firstNormal = null; }
  5715. for (var p = 0; p < path.length; p++) {
  5716. this._curve[p].x = path[p].x;
  5717. this._curve[p].y = path[p].y;
  5718. this._curve[p].z = path[p].z;
  5719. }
  5720. this._compute(firstNormal);
  5721. return this;
  5722. };
  5723. // private function compute() : computes tangents, normals and binormals
  5724. Path3D.prototype._compute = function (firstNormal) {
  5725. var l = this._curve.length;
  5726. // first and last tangents
  5727. this._tangents[0] = this._getFirstNonNullVector(0);
  5728. if (!this._raw) {
  5729. this._tangents[0].normalize();
  5730. }
  5731. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5732. if (!this._raw) {
  5733. this._tangents[l - 1].normalize();
  5734. }
  5735. // normals and binormals at first point : arbitrary vector with _normalVector()
  5736. var tg0 = this._tangents[0];
  5737. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5738. this._normals[0] = pp0;
  5739. if (!this._raw) {
  5740. this._normals[0].normalize();
  5741. }
  5742. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5743. if (!this._raw) {
  5744. this._binormals[0].normalize();
  5745. }
  5746. this._distances[0] = 0.0;
  5747. // normals and binormals : next points
  5748. var prev; // previous vector (segment)
  5749. var cur; // current vector (segment)
  5750. var curTang; // current tangent
  5751. // previous normal
  5752. var prevBinor; // previous binormal
  5753. for (var i = 1; i < l; i++) {
  5754. // tangents
  5755. prev = this._getLastNonNullVector(i);
  5756. if (i < l - 1) {
  5757. cur = this._getFirstNonNullVector(i);
  5758. this._tangents[i] = prev.add(cur);
  5759. this._tangents[i].normalize();
  5760. }
  5761. this._distances[i] = this._distances[i - 1] + prev.length();
  5762. // normals and binormals
  5763. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5764. curTang = this._tangents[i];
  5765. prevBinor = this._binormals[i - 1];
  5766. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5767. if (!this._raw) {
  5768. this._normals[i].normalize();
  5769. }
  5770. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5771. if (!this._raw) {
  5772. this._binormals[i].normalize();
  5773. }
  5774. }
  5775. };
  5776. // private function getFirstNonNullVector(index)
  5777. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5778. Path3D.prototype._getFirstNonNullVector = function (index) {
  5779. var i = 1;
  5780. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5781. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5782. i++;
  5783. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5784. }
  5785. return nNVector;
  5786. };
  5787. // private function getLastNonNullVector(index)
  5788. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5789. Path3D.prototype._getLastNonNullVector = function (index) {
  5790. var i = 1;
  5791. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5792. while (nLVector.length() === 0 && index > i + 1) {
  5793. i++;
  5794. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5795. }
  5796. return nLVector;
  5797. };
  5798. // private function normalVector(v0, vt, va) :
  5799. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5800. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5801. Path3D.prototype._normalVector = function (v0, vt, va) {
  5802. var normal0;
  5803. var tgl = vt.length();
  5804. if (tgl === 0.0) {
  5805. tgl = 1.0;
  5806. }
  5807. if (va === undefined || va === null) {
  5808. var point;
  5809. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5810. point = new Vector3(0.0, -1.0, 0.0);
  5811. }
  5812. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5813. point = new Vector3(1.0, 0.0, 0.0);
  5814. }
  5815. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5816. point = new Vector3(0.0, 0.0, 1.0);
  5817. }
  5818. else {
  5819. point = Vector3.Zero();
  5820. }
  5821. normal0 = Vector3.Cross(vt, point);
  5822. }
  5823. else {
  5824. normal0 = Vector3.Cross(vt, va);
  5825. Vector3.CrossToRef(normal0, vt, normal0);
  5826. }
  5827. normal0.normalize();
  5828. return normal0;
  5829. };
  5830. return Path3D;
  5831. }());
  5832. BABYLON.Path3D = Path3D;
  5833. var Curve3 = /** @class */ (function () {
  5834. /**
  5835. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5836. * A Curve3 is designed from a series of successive Vector3.
  5837. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5838. */
  5839. function Curve3(points) {
  5840. this._length = 0.0;
  5841. this._points = points;
  5842. this._length = this._computeLength(points);
  5843. }
  5844. /**
  5845. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5846. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5847. * @param v1 (Vector3) the control point
  5848. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5849. * @param nbPoints (integer) the wanted number of points in the curve
  5850. */
  5851. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5852. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5853. var bez = new Array();
  5854. var equation = function (t, val0, val1, val2) {
  5855. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5856. return res;
  5857. };
  5858. for (var i = 0; i <= nbPoints; i++) {
  5859. 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)));
  5860. }
  5861. return new Curve3(bez);
  5862. };
  5863. /**
  5864. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5865. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5866. * @param v1 (Vector3) the first control point
  5867. * @param v2 (Vector3) the second control point
  5868. * @param v3 (Vector3) the end point of the Cubic Bezier
  5869. * @param nbPoints (integer) the wanted number of points in the curve
  5870. */
  5871. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5872. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5873. var bez = new Array();
  5874. var equation = function (t, val0, val1, val2, val3) {
  5875. 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;
  5876. return res;
  5877. };
  5878. for (var i = 0; i <= nbPoints; i++) {
  5879. 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)));
  5880. }
  5881. return new Curve3(bez);
  5882. };
  5883. /**
  5884. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5885. * @param p1 (Vector3) the origin point of the Hermite Spline
  5886. * @param t1 (Vector3) the tangent vector at the origin point
  5887. * @param p2 (Vector3) the end point of the Hermite Spline
  5888. * @param t2 (Vector3) the tangent vector at the end point
  5889. * @param nbPoints (integer) the wanted number of points in the curve
  5890. */
  5891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5892. var hermite = new Array();
  5893. var step = 1.0 / nbPoints;
  5894. for (var i = 0; i <= nbPoints; i++) {
  5895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5896. }
  5897. return new Curve3(hermite);
  5898. };
  5899. /**
  5900. * Returns a Curve3 object along a CatmullRom Spline curve :
  5901. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5902. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5903. */
  5904. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5905. var totalPoints = new Array();
  5906. totalPoints.push(points[0].clone());
  5907. Array.prototype.push.apply(totalPoints, points);
  5908. totalPoints.push(points[points.length - 1].clone());
  5909. var catmullRom = new Array();
  5910. var step = 1.0 / nbPoints;
  5911. var amount = 0.0;
  5912. for (var i = 0; i < totalPoints.length - 3; i++) {
  5913. amount = 0;
  5914. for (var c = 0; c < nbPoints; c++) {
  5915. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5916. amount += step;
  5917. }
  5918. }
  5919. i--;
  5920. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5921. return new Curve3(catmullRom);
  5922. };
  5923. /**
  5924. * Returns the Curve3 stored array of successive Vector3
  5925. */
  5926. Curve3.prototype.getPoints = function () {
  5927. return this._points;
  5928. };
  5929. /**
  5930. * Returns the computed length (float) of the curve.
  5931. */
  5932. Curve3.prototype.length = function () {
  5933. return this._length;
  5934. };
  5935. /**
  5936. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5937. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5938. * curveA and curveB keep unchanged.
  5939. */
  5940. Curve3.prototype.continue = function (curve) {
  5941. var lastPoint = this._points[this._points.length - 1];
  5942. var continuedPoints = this._points.slice();
  5943. var curvePoints = curve.getPoints();
  5944. for (var i = 1; i < curvePoints.length; i++) {
  5945. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5946. }
  5947. var continuedCurve = new Curve3(continuedPoints);
  5948. return continuedCurve;
  5949. };
  5950. Curve3.prototype._computeLength = function (path) {
  5951. var l = 0;
  5952. for (var i = 1; i < path.length; i++) {
  5953. l += (path[i].subtract(path[i - 1])).length();
  5954. }
  5955. return l;
  5956. };
  5957. return Curve3;
  5958. }());
  5959. BABYLON.Curve3 = Curve3;
  5960. // Vertex formats
  5961. var PositionNormalVertex = /** @class */ (function () {
  5962. function PositionNormalVertex(position, normal) {
  5963. if (position === void 0) { position = Vector3.Zero(); }
  5964. if (normal === void 0) { normal = Vector3.Up(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. }
  5968. PositionNormalVertex.prototype.clone = function () {
  5969. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5970. };
  5971. return PositionNormalVertex;
  5972. }());
  5973. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5974. var PositionNormalTextureVertex = /** @class */ (function () {
  5975. function PositionNormalTextureVertex(position, normal, uv) {
  5976. if (position === void 0) { position = Vector3.Zero(); }
  5977. if (normal === void 0) { normal = Vector3.Up(); }
  5978. if (uv === void 0) { uv = Vector2.Zero(); }
  5979. this.position = position;
  5980. this.normal = normal;
  5981. this.uv = uv;
  5982. }
  5983. PositionNormalTextureVertex.prototype.clone = function () {
  5984. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5985. };
  5986. return PositionNormalTextureVertex;
  5987. }());
  5988. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5989. // Temporary pre-allocated objects for engine internal use
  5990. // usage in any internal function :
  5991. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5992. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5993. var Tmp = /** @class */ (function () {
  5994. function Tmp() {
  5995. }
  5996. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5997. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5998. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5999. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6000. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6001. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6002. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6003. Matrix.Zero(), Matrix.Zero(),
  6004. Matrix.Zero(), Matrix.Zero(),
  6005. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6006. return Tmp;
  6007. }());
  6008. BABYLON.Tmp = Tmp;
  6009. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6010. var MathTmp = /** @class */ (function () {
  6011. function MathTmp() {
  6012. }
  6013. MathTmp.Vector3 = [Vector3.Zero()];
  6014. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6015. MathTmp.Quaternion = [Quaternion.Zero()];
  6016. return MathTmp;
  6017. }());
  6018. })(BABYLON || (BABYLON = {}));
  6019. //# sourceMappingURL=babylon.math.js.map
  6020. var BABYLON;
  6021. (function (BABYLON) {
  6022. var Scalar = /** @class */ (function () {
  6023. function Scalar() {
  6024. }
  6025. /**
  6026. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6027. */
  6028. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6029. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6030. var num = a - b;
  6031. return -epsilon <= num && num <= epsilon;
  6032. };
  6033. /**
  6034. * Returns a string : the upper case translation of the number i to hexadecimal.
  6035. */
  6036. Scalar.ToHex = function (i) {
  6037. var str = i.toString(16);
  6038. if (i <= 15) {
  6039. return ("0" + str).toUpperCase();
  6040. }
  6041. return str.toUpperCase();
  6042. };
  6043. /**
  6044. * Returns -1 if value is negative and +1 is value is positive.
  6045. * Returns the value itself if it's equal to zero.
  6046. */
  6047. Scalar.Sign = function (value) {
  6048. value = +value; // convert to a number
  6049. if (value === 0 || isNaN(value))
  6050. return value;
  6051. return value > 0 ? 1 : -1;
  6052. };
  6053. /**
  6054. * Returns the value itself if it's between min and max.
  6055. * Returns min if the value is lower than min.
  6056. * Returns max if the value is greater than max.
  6057. */
  6058. Scalar.Clamp = function (value, min, max) {
  6059. if (min === void 0) { min = 0; }
  6060. if (max === void 0) { max = 1; }
  6061. return Math.min(max, Math.max(min, value));
  6062. };
  6063. /**
  6064. * Returns the log2 of value.
  6065. */
  6066. Scalar.Log2 = function (value) {
  6067. return Math.log(value) * Math.LOG2E;
  6068. };
  6069. /**
  6070. * Loops the value, so that it is never larger than length and never smaller than 0.
  6071. *
  6072. * This is similar to the modulo operator but it works with floating point numbers.
  6073. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6074. * With t = 5 and length = 2.5, the result would be 0.0.
  6075. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6076. */
  6077. Scalar.Repeat = function (value, length) {
  6078. return value - Math.floor(value / length) * length;
  6079. };
  6080. /**
  6081. * Normalize the value between 0.0 and 1.0 using min and max values
  6082. */
  6083. Scalar.Normalize = function (value, min, max) {
  6084. return (value - min) / (max - min);
  6085. };
  6086. /**
  6087. * Denormalize the value from 0.0 and 1.0 using min and max values
  6088. */
  6089. Scalar.Denormalize = function (normalized, min, max) {
  6090. return (normalized * (max - min) + min);
  6091. };
  6092. /**
  6093. * Calculates the shortest difference between two given angles given in degrees.
  6094. */
  6095. Scalar.DeltaAngle = function (current, target) {
  6096. var num = Scalar.Repeat(target - current, 360.0);
  6097. if (num > 180.0) {
  6098. num -= 360.0;
  6099. }
  6100. return num;
  6101. };
  6102. /**
  6103. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6104. *
  6105. * The returned value will move back and forth between 0 and length
  6106. */
  6107. Scalar.PingPong = function (tx, length) {
  6108. var t = Scalar.Repeat(tx, length * 2.0);
  6109. return length - Math.abs(t - length);
  6110. };
  6111. /**
  6112. * Interpolates between min and max with smoothing at the limits.
  6113. *
  6114. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6115. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6116. */
  6117. Scalar.SmoothStep = function (from, to, tx) {
  6118. var t = Scalar.Clamp(tx);
  6119. t = -2.0 * t * t * t + 3.0 * t * t;
  6120. return to * t + from * (1.0 - t);
  6121. };
  6122. /**
  6123. * Moves a value current towards target.
  6124. *
  6125. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6126. * Negative values of maxDelta pushes the value away from target.
  6127. */
  6128. Scalar.MoveTowards = function (current, target, maxDelta) {
  6129. var result = 0;
  6130. if (Math.abs(target - current) <= maxDelta) {
  6131. result = target;
  6132. }
  6133. else {
  6134. result = current + Scalar.Sign(target - current) * maxDelta;
  6135. }
  6136. return result;
  6137. };
  6138. /**
  6139. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6140. *
  6141. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6142. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6143. */
  6144. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6145. var num = Scalar.DeltaAngle(current, target);
  6146. var result = 0;
  6147. if (-maxDelta < num && num < maxDelta) {
  6148. result = target;
  6149. }
  6150. else {
  6151. target = current + num;
  6152. result = Scalar.MoveTowards(current, target, maxDelta);
  6153. }
  6154. return result;
  6155. };
  6156. /**
  6157. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6158. */
  6159. Scalar.Lerp = function (start, end, amount) {
  6160. return start + ((end - start) * amount);
  6161. };
  6162. /**
  6163. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6164. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6165. */
  6166. Scalar.LerpAngle = function (start, end, amount) {
  6167. var num = Scalar.Repeat(end - start, 360.0);
  6168. if (num > 180.0) {
  6169. num -= 360.0;
  6170. }
  6171. return start + num * Scalar.Clamp(amount);
  6172. };
  6173. /**
  6174. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6175. */
  6176. Scalar.InverseLerp = function (a, b, value) {
  6177. var result = 0;
  6178. if (a != b) {
  6179. result = Scalar.Clamp((value - a) / (b - a));
  6180. }
  6181. else {
  6182. result = 0.0;
  6183. }
  6184. return result;
  6185. };
  6186. /**
  6187. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6188. */
  6189. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6190. var squared = amount * amount;
  6191. var cubed = amount * squared;
  6192. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6193. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6194. var part3 = (cubed - (2.0 * squared)) + amount;
  6195. var part4 = cubed - squared;
  6196. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6197. };
  6198. /**
  6199. * Returns a random float number between and min and max values
  6200. */
  6201. Scalar.RandomRange = function (min, max) {
  6202. if (min === max)
  6203. return min;
  6204. return ((Math.random() * (max - min)) + min);
  6205. };
  6206. /**
  6207. * This function returns percentage of a number in a given range.
  6208. *
  6209. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6210. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6211. */
  6212. Scalar.RangeToPercent = function (number, min, max) {
  6213. return ((number - min) / (max - min));
  6214. };
  6215. /**
  6216. * This function returns number that corresponds to the percentage in a given range.
  6217. *
  6218. * PercentToRange(0.34,0,100) will return 34.
  6219. */
  6220. Scalar.PercentToRange = function (percent, min, max) {
  6221. return ((max - min) * percent + min);
  6222. };
  6223. /**
  6224. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6225. * @param angle The angle to normalize in radian.
  6226. * @return The converted angle.
  6227. */
  6228. Scalar.NormalizeRadians = function (angle) {
  6229. // More precise but slower version kept for reference.
  6230. // angle = angle % Tools.TwoPi;
  6231. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6232. //if (angle > Math.PI) {
  6233. // angle -= Tools.TwoPi;
  6234. //}
  6235. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6236. return angle;
  6237. };
  6238. /**
  6239. * Two pi constants convenient for computation.
  6240. */
  6241. Scalar.TwoPi = Math.PI * 2;
  6242. return Scalar;
  6243. }());
  6244. BABYLON.Scalar = Scalar;
  6245. })(BABYLON || (BABYLON = {}));
  6246. //# sourceMappingURL=babylon.math.scalar.js.map
  6247. //# sourceMappingURL=babylon.mixins.js.map
  6248. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6249. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6250. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6251. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6252. //# sourceMappingURL=babylon.webgl2.js.map
  6253. var BABYLON;
  6254. (function (BABYLON) {
  6255. var __decoratorInitialStore = {};
  6256. var __mergedStore = {};
  6257. var _copySource = function (creationFunction, source, instanciate) {
  6258. var destination = creationFunction();
  6259. // Tags
  6260. if (BABYLON.Tags) {
  6261. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6262. }
  6263. var classStore = getMergedStore(destination);
  6264. // Properties
  6265. for (var property in classStore) {
  6266. var propertyDescriptor = classStore[property];
  6267. var sourceProperty = source[property];
  6268. var propertyType = propertyDescriptor.type;
  6269. if (sourceProperty !== undefined && sourceProperty !== null) {
  6270. switch (propertyType) {
  6271. case 0: // Value
  6272. case 6:// Mesh reference
  6273. destination[property] = sourceProperty;
  6274. break;
  6275. case 1:// Texture
  6276. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6277. break;
  6278. case 2: // Color3
  6279. case 3: // FresnelParameters
  6280. case 4: // Vector2
  6281. case 5: // Vector3
  6282. case 7: // Color Curves
  6283. case 10:// Quaternion
  6284. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6285. break;
  6286. }
  6287. }
  6288. }
  6289. return destination;
  6290. };
  6291. function getDirectStore(target) {
  6292. var classKey = target.getClassName();
  6293. if (!__decoratorInitialStore[classKey]) {
  6294. __decoratorInitialStore[classKey] = {};
  6295. }
  6296. return __decoratorInitialStore[classKey];
  6297. }
  6298. /**
  6299. * Return the list of properties flagged as serializable
  6300. * @param target: host object
  6301. */
  6302. function getMergedStore(target) {
  6303. var classKey = target.getClassName();
  6304. if (__mergedStore[classKey]) {
  6305. return __mergedStore[classKey];
  6306. }
  6307. __mergedStore[classKey] = {};
  6308. var store = __mergedStore[classKey];
  6309. var currentTarget = target;
  6310. var currentKey = classKey;
  6311. while (currentKey) {
  6312. var initialStore = __decoratorInitialStore[currentKey];
  6313. for (var property in initialStore) {
  6314. store[property] = initialStore[property];
  6315. }
  6316. var parent_1 = void 0;
  6317. var done = false;
  6318. do {
  6319. parent_1 = Object.getPrototypeOf(currentTarget);
  6320. if (!parent_1.getClassName) {
  6321. done = true;
  6322. break;
  6323. }
  6324. if (parent_1.getClassName() !== currentKey) {
  6325. break;
  6326. }
  6327. currentTarget = parent_1;
  6328. } while (parent_1);
  6329. if (done) {
  6330. break;
  6331. }
  6332. currentKey = parent_1.getClassName();
  6333. currentTarget = parent_1;
  6334. }
  6335. return store;
  6336. }
  6337. function generateSerializableMember(type, sourceName) {
  6338. return function (target, propertyKey) {
  6339. var classStore = getDirectStore(target);
  6340. if (!classStore[propertyKey]) {
  6341. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6342. }
  6343. };
  6344. }
  6345. function generateExpandMember(setCallback, targetKey) {
  6346. if (targetKey === void 0) { targetKey = null; }
  6347. return function (target, propertyKey) {
  6348. var key = targetKey || ("_" + propertyKey);
  6349. Object.defineProperty(target, propertyKey, {
  6350. get: function () {
  6351. return this[key];
  6352. },
  6353. set: function (value) {
  6354. if (this[key] === value) {
  6355. return;
  6356. }
  6357. this[key] = value;
  6358. target[setCallback].apply(this);
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. };
  6364. }
  6365. function expandToProperty(callback, targetKey) {
  6366. if (targetKey === void 0) { targetKey = null; }
  6367. return generateExpandMember(callback, targetKey);
  6368. }
  6369. BABYLON.expandToProperty = expandToProperty;
  6370. function serialize(sourceName) {
  6371. return generateSerializableMember(0, sourceName); // value member
  6372. }
  6373. BABYLON.serialize = serialize;
  6374. function serializeAsTexture(sourceName) {
  6375. return generateSerializableMember(1, sourceName); // texture member
  6376. }
  6377. BABYLON.serializeAsTexture = serializeAsTexture;
  6378. function serializeAsColor3(sourceName) {
  6379. return generateSerializableMember(2, sourceName); // color3 member
  6380. }
  6381. BABYLON.serializeAsColor3 = serializeAsColor3;
  6382. function serializeAsFresnelParameters(sourceName) {
  6383. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6384. }
  6385. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6386. function serializeAsVector2(sourceName) {
  6387. return generateSerializableMember(4, sourceName); // vector2 member
  6388. }
  6389. BABYLON.serializeAsVector2 = serializeAsVector2;
  6390. function serializeAsVector3(sourceName) {
  6391. return generateSerializableMember(5, sourceName); // vector3 member
  6392. }
  6393. BABYLON.serializeAsVector3 = serializeAsVector3;
  6394. function serializeAsMeshReference(sourceName) {
  6395. return generateSerializableMember(6, sourceName); // mesh reference member
  6396. }
  6397. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6398. function serializeAsColorCurves(sourceName) {
  6399. return generateSerializableMember(7, sourceName); // color curves
  6400. }
  6401. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6402. function serializeAsColor4(sourceName) {
  6403. return generateSerializableMember(8, sourceName); // color 4
  6404. }
  6405. BABYLON.serializeAsColor4 = serializeAsColor4;
  6406. function serializeAsImageProcessingConfiguration(sourceName) {
  6407. return generateSerializableMember(9, sourceName); // image processing
  6408. }
  6409. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6410. function serializeAsQuaternion(sourceName) {
  6411. return generateSerializableMember(10, sourceName); // quaternion member
  6412. }
  6413. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6414. var SerializationHelper = /** @class */ (function () {
  6415. function SerializationHelper() {
  6416. }
  6417. SerializationHelper.Serialize = function (entity, serializationObject) {
  6418. if (!serializationObject) {
  6419. serializationObject = {};
  6420. }
  6421. // Tags
  6422. if (BABYLON.Tags) {
  6423. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6424. }
  6425. var serializedProperties = getMergedStore(entity);
  6426. // Properties
  6427. for (var property in serializedProperties) {
  6428. var propertyDescriptor = serializedProperties[property];
  6429. var targetPropertyName = propertyDescriptor.sourceName || property;
  6430. var propertyType = propertyDescriptor.type;
  6431. var sourceProperty = entity[property];
  6432. if (sourceProperty !== undefined && sourceProperty !== null) {
  6433. switch (propertyType) {
  6434. case 0:// Value
  6435. serializationObject[targetPropertyName] = sourceProperty;
  6436. break;
  6437. case 1:// Texture
  6438. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6439. break;
  6440. case 2:// Color3
  6441. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6442. break;
  6443. case 3:// FresnelParameters
  6444. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6445. break;
  6446. case 4:// Vector2
  6447. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6448. break;
  6449. case 5:// Vector3
  6450. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6451. break;
  6452. case 6:// Mesh reference
  6453. serializationObject[targetPropertyName] = sourceProperty.id;
  6454. break;
  6455. case 7:// Color Curves
  6456. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6457. break;
  6458. case 8:// Color 4
  6459. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6460. break;
  6461. case 9:// Image Processing
  6462. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6463. break;
  6464. }
  6465. }
  6466. }
  6467. return serializationObject;
  6468. };
  6469. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6470. if (rootUrl === void 0) { rootUrl = null; }
  6471. var destination = creationFunction();
  6472. if (!rootUrl) {
  6473. rootUrl = "";
  6474. }
  6475. // Tags
  6476. if (BABYLON.Tags) {
  6477. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6478. }
  6479. var classStore = getMergedStore(destination);
  6480. // Properties
  6481. for (var property in classStore) {
  6482. var propertyDescriptor = classStore[property];
  6483. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6484. var propertyType = propertyDescriptor.type;
  6485. if (sourceProperty !== undefined && sourceProperty !== null) {
  6486. var dest = destination;
  6487. switch (propertyType) {
  6488. case 0:// Value
  6489. dest[property] = sourceProperty;
  6490. break;
  6491. case 1:// Texture
  6492. if (scene) {
  6493. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6494. }
  6495. break;
  6496. case 2:// Color3
  6497. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6498. break;
  6499. case 3:// FresnelParameters
  6500. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6501. break;
  6502. case 4:// Vector2
  6503. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6504. break;
  6505. case 5:// Vector3
  6506. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6507. break;
  6508. case 6:// Mesh reference
  6509. if (scene) {
  6510. dest[property] = scene.getLastMeshByID(sourceProperty);
  6511. }
  6512. break;
  6513. case 7:// Color Curves
  6514. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6515. break;
  6516. case 8:// Color 4
  6517. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6518. break;
  6519. case 9:// Image Processing
  6520. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6521. break;
  6522. }
  6523. }
  6524. }
  6525. return destination;
  6526. };
  6527. SerializationHelper.Clone = function (creationFunction, source) {
  6528. return _copySource(creationFunction, source, false);
  6529. };
  6530. SerializationHelper.Instanciate = function (creationFunction, source) {
  6531. return _copySource(creationFunction, source, true);
  6532. };
  6533. return SerializationHelper;
  6534. }());
  6535. BABYLON.SerializationHelper = SerializationHelper;
  6536. })(BABYLON || (BABYLON = {}));
  6537. //# sourceMappingURL=babylon.decorators.js.map
  6538. var BABYLON;
  6539. (function (BABYLON) {
  6540. /**
  6541. * A class serves as a medium between the observable and its observers
  6542. */
  6543. var EventState = /** @class */ (function () {
  6544. /**
  6545. * Create a new EventState
  6546. * @param mask defines the mask associated with this state
  6547. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  6548. * @param target defines the original target of the state
  6549. * @param currentTarget defines the current target of the state
  6550. */
  6551. function EventState(mask, skipNextObservers, target, currentTarget) {
  6552. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6553. this.initalize(mask, skipNextObservers, target, currentTarget);
  6554. }
  6555. /**
  6556. * Initialize the current event state
  6557. * @param mask defines the mask associated with this state
  6558. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  6559. * @param target defines the original target of the state
  6560. * @param currentTarget defines the current target of the state
  6561. * @returns the current event state
  6562. */
  6563. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6564. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6565. this.mask = mask;
  6566. this.skipNextObservers = skipNextObservers;
  6567. this.target = target;
  6568. this.currentTarget = currentTarget;
  6569. return this;
  6570. };
  6571. return EventState;
  6572. }());
  6573. BABYLON.EventState = EventState;
  6574. /**
  6575. * Represent an Observer registered to a given Observable object.
  6576. */
  6577. var Observer = /** @class */ (function () {
  6578. /**
  6579. * Creates a new observer
  6580. * @param callback defines the callback to call when the observer is notified
  6581. * @param mask defines the mask of the observer (used to filter notifications)
  6582. * @param scope defines the current scope used to restore the JS context
  6583. */
  6584. function Observer(
  6585. /**
  6586. * Defines the callback to call when the observer is notified
  6587. */
  6588. callback,
  6589. /**
  6590. * Defines the mask of the observer (used to filter notifications)
  6591. */
  6592. mask,
  6593. /**
  6594. * Defines the current scope used to restore the JS context
  6595. */
  6596. scope) {
  6597. if (scope === void 0) { scope = null; }
  6598. this.callback = callback;
  6599. this.mask = mask;
  6600. this.scope = scope;
  6601. /**
  6602. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  6603. */
  6604. this.unregisterOnNextCall = false;
  6605. }
  6606. return Observer;
  6607. }());
  6608. BABYLON.Observer = Observer;
  6609. /**
  6610. * Represent a list of observers registered to multiple Observables object.
  6611. */
  6612. var MultiObserver = /** @class */ (function () {
  6613. function MultiObserver() {
  6614. }
  6615. /**
  6616. * Release associated resources
  6617. */
  6618. MultiObserver.prototype.dispose = function () {
  6619. if (this._observers && this._observables) {
  6620. for (var index = 0; index < this._observers.length; index++) {
  6621. this._observables[index].remove(this._observers[index]);
  6622. }
  6623. }
  6624. this._observers = null;
  6625. this._observables = null;
  6626. };
  6627. /**
  6628. * Raise a callback when one of the observable will notify
  6629. * @param observables defines a list of observables to watch
  6630. * @param callback defines the callback to call on notification
  6631. * @param mask defines the mask used to filter notifications
  6632. * @param scope defines the current scope used to restore the JS context
  6633. * @returns the new MultiObserver
  6634. */
  6635. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6636. if (mask === void 0) { mask = -1; }
  6637. if (scope === void 0) { scope = null; }
  6638. var result = new MultiObserver();
  6639. result._observers = new Array();
  6640. result._observables = observables;
  6641. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6642. var observable = observables_1[_i];
  6643. var observer = observable.add(callback, mask, false, scope);
  6644. if (observer) {
  6645. result._observers.push(observer);
  6646. }
  6647. }
  6648. return result;
  6649. };
  6650. return MultiObserver;
  6651. }());
  6652. BABYLON.MultiObserver = MultiObserver;
  6653. /**
  6654. * The Observable class is a simple implementation of the Observable pattern.
  6655. * 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.
  6656. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6657. * 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).
  6658. * 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.
  6659. */
  6660. var Observable = /** @class */ (function () {
  6661. /**
  6662. * Creates a new observable
  6663. * @param onObserverAdded defines a callback to call when a new observer is added
  6664. */
  6665. function Observable(onObserverAdded) {
  6666. this._observers = new Array();
  6667. this._eventState = new EventState(0);
  6668. if (onObserverAdded) {
  6669. this._onObserverAdded = onObserverAdded;
  6670. }
  6671. }
  6672. /**
  6673. * Create a new Observer with the specified callback
  6674. * @param callback the callback that will be executed for that Observer
  6675. * @param mask the mask used to filter observers
  6676. * @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.
  6677. * @param scope optional scope for the callback to be called from
  6678. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  6679. * @returns the new observer created for the callback
  6680. */
  6681. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  6682. if (mask === void 0) { mask = -1; }
  6683. if (insertFirst === void 0) { insertFirst = false; }
  6684. if (scope === void 0) { scope = null; }
  6685. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  6686. if (!callback) {
  6687. return null;
  6688. }
  6689. var observer = new Observer(callback, mask, scope);
  6690. observer.unregisterOnNextCall = unregisterOnFirstCall;
  6691. if (insertFirst) {
  6692. this._observers.unshift(observer);
  6693. }
  6694. else {
  6695. this._observers.push(observer);
  6696. }
  6697. if (this._onObserverAdded) {
  6698. this._onObserverAdded(observer);
  6699. }
  6700. return observer;
  6701. };
  6702. /**
  6703. * Remove an Observer from the Observable object
  6704. * @param observer the instance of the Observer to remove
  6705. * @returns false if it doesn't belong to this Observable
  6706. */
  6707. Observable.prototype.remove = function (observer) {
  6708. if (!observer) {
  6709. return false;
  6710. }
  6711. var index = this._observers.indexOf(observer);
  6712. if (index !== -1) {
  6713. this._observers.splice(index, 1);
  6714. return true;
  6715. }
  6716. return false;
  6717. };
  6718. /**
  6719. * Remove a callback from the Observable object
  6720. * @param callback the callback to remove
  6721. * @param scope optional scope. If used only the callbacks with this scope will be removed
  6722. * @returns false if it doesn't belong to this Observable
  6723. */
  6724. Observable.prototype.removeCallback = function (callback, scope) {
  6725. for (var index = 0; index < this._observers.length; index++) {
  6726. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6727. this._observers.splice(index, 1);
  6728. return true;
  6729. }
  6730. }
  6731. return false;
  6732. };
  6733. Observable.prototype._deferUnregister = function (observer) {
  6734. var _this = this;
  6735. BABYLON.Tools.SetImmediate(function () {
  6736. _this.remove(observer);
  6737. });
  6738. };
  6739. /**
  6740. * Notify all Observers by calling their respective callback with the given data
  6741. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6742. * @param eventData defines the data to send to all observers
  6743. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  6744. * @param target defines the original target of the state
  6745. * @param currentTarget defines the current target of the state
  6746. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  6747. */
  6748. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6749. if (mask === void 0) { mask = -1; }
  6750. if (!this._observers.length) {
  6751. return true;
  6752. }
  6753. var state = this._eventState;
  6754. state.mask = mask;
  6755. state.target = target;
  6756. state.currentTarget = currentTarget;
  6757. state.skipNextObservers = false;
  6758. state.lastReturnValue = eventData;
  6759. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6760. var obs = _a[_i];
  6761. if (obs.mask & mask) {
  6762. if (obs.scope) {
  6763. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6764. }
  6765. else {
  6766. state.lastReturnValue = obs.callback(eventData, state);
  6767. }
  6768. if (obs.unregisterOnNextCall) {
  6769. this._deferUnregister(obs);
  6770. }
  6771. }
  6772. if (state.skipNextObservers) {
  6773. return false;
  6774. }
  6775. }
  6776. return true;
  6777. };
  6778. /**
  6779. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6780. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6781. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6782. * and it is crucial that all callbacks will be executed.
  6783. * The order of the callbacks is kept, callbacks are not executed parallel.
  6784. *
  6785. * @param eventData The data to be sent to each callback
  6786. * @param mask is used to filter observers defaults to -1
  6787. * @param target defines the callback target (see EventState)
  6788. * @param currentTarget defines he current object in the bubbling phase
  6789. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6790. */
  6791. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6792. var _this = this;
  6793. if (mask === void 0) { mask = -1; }
  6794. // create an empty promise
  6795. var p = Promise.resolve(eventData);
  6796. // no observers? return this promise.
  6797. if (!this._observers.length) {
  6798. return p;
  6799. }
  6800. var state = this._eventState;
  6801. state.mask = mask;
  6802. state.target = target;
  6803. state.currentTarget = currentTarget;
  6804. state.skipNextObservers = false;
  6805. // execute one callback after another (not using Promise.all, the order is important)
  6806. this._observers.forEach(function (obs) {
  6807. if (state.skipNextObservers) {
  6808. return;
  6809. }
  6810. if (obs.mask & mask) {
  6811. if (obs.scope) {
  6812. p = p.then(function (lastReturnedValue) {
  6813. state.lastReturnValue = lastReturnedValue;
  6814. return obs.callback.apply(obs.scope, [eventData, state]);
  6815. });
  6816. }
  6817. else {
  6818. p = p.then(function (lastReturnedValue) {
  6819. state.lastReturnValue = lastReturnedValue;
  6820. return obs.callback(eventData, state);
  6821. });
  6822. }
  6823. if (obs.unregisterOnNextCall) {
  6824. _this._deferUnregister(obs);
  6825. }
  6826. }
  6827. });
  6828. // return the eventData
  6829. return p.then(function () { return eventData; });
  6830. };
  6831. /**
  6832. * Notify a specific observer
  6833. * @param observer defines the observer to notify
  6834. * @param eventData defines the data to be sent to each callback
  6835. * @param mask is used to filter observers defaults to -1
  6836. */
  6837. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6838. if (mask === void 0) { mask = -1; }
  6839. var state = this._eventState;
  6840. state.mask = mask;
  6841. state.skipNextObservers = false;
  6842. observer.callback(eventData, state);
  6843. };
  6844. /**
  6845. * Gets a boolean indicating if the observable has at least one observer
  6846. * @returns true is the Observable has at least one Observer registered
  6847. */
  6848. Observable.prototype.hasObservers = function () {
  6849. return this._observers.length > 0;
  6850. };
  6851. /**
  6852. * Clear the list of observers
  6853. */
  6854. Observable.prototype.clear = function () {
  6855. this._observers = new Array();
  6856. this._onObserverAdded = null;
  6857. };
  6858. /**
  6859. * Clone the current observable
  6860. * @returns a new observable
  6861. */
  6862. Observable.prototype.clone = function () {
  6863. var result = new Observable();
  6864. result._observers = this._observers.slice(0);
  6865. return result;
  6866. };
  6867. /**
  6868. * Does this observable handles observer registered with a given mask
  6869. * @param mask defines the mask to be tested
  6870. * @return whether or not one observer registered with the given mask is handeled
  6871. **/
  6872. Observable.prototype.hasSpecificMask = function (mask) {
  6873. if (mask === void 0) { mask = -1; }
  6874. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6875. var obs = _a[_i];
  6876. if (obs.mask & mask || obs.mask === mask) {
  6877. return true;
  6878. }
  6879. }
  6880. return false;
  6881. };
  6882. return Observable;
  6883. }());
  6884. BABYLON.Observable = Observable;
  6885. })(BABYLON || (BABYLON = {}));
  6886. //# sourceMappingURL=babylon.observable.js.map
  6887. var BABYLON;
  6888. (function (BABYLON) {
  6889. var SmartArray = /** @class */ (function () {
  6890. function SmartArray(capacity) {
  6891. this.length = 0;
  6892. this.data = new Array(capacity);
  6893. this._id = SmartArray._GlobalId++;
  6894. }
  6895. SmartArray.prototype.push = function (value) {
  6896. this.data[this.length++] = value;
  6897. if (this.length > this.data.length) {
  6898. this.data.length *= 2;
  6899. }
  6900. };
  6901. SmartArray.prototype.forEach = function (func) {
  6902. for (var index = 0; index < this.length; index++) {
  6903. func(this.data[index]);
  6904. }
  6905. };
  6906. SmartArray.prototype.sort = function (compareFn) {
  6907. this.data.sort(compareFn);
  6908. };
  6909. SmartArray.prototype.reset = function () {
  6910. this.length = 0;
  6911. };
  6912. SmartArray.prototype.dispose = function () {
  6913. this.reset();
  6914. if (this.data) {
  6915. this.data.length = 0;
  6916. this.data = [];
  6917. }
  6918. };
  6919. SmartArray.prototype.concat = function (array) {
  6920. if (array.length === 0) {
  6921. return;
  6922. }
  6923. if (this.length + array.length > this.data.length) {
  6924. this.data.length = (this.length + array.length) * 2;
  6925. }
  6926. for (var index = 0; index < array.length; index++) {
  6927. this.data[this.length++] = (array.data || array)[index];
  6928. }
  6929. };
  6930. SmartArray.prototype.indexOf = function (value) {
  6931. var position = this.data.indexOf(value);
  6932. if (position >= this.length) {
  6933. return -1;
  6934. }
  6935. return position;
  6936. };
  6937. SmartArray.prototype.contains = function (value) {
  6938. return this.data.indexOf(value) !== -1;
  6939. };
  6940. // Statics
  6941. SmartArray._GlobalId = 0;
  6942. return SmartArray;
  6943. }());
  6944. BABYLON.SmartArray = SmartArray;
  6945. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6946. __extends(SmartArrayNoDuplicate, _super);
  6947. function SmartArrayNoDuplicate() {
  6948. var _this = _super !== null && _super.apply(this, arguments) || this;
  6949. _this._duplicateId = 0;
  6950. return _this;
  6951. }
  6952. SmartArrayNoDuplicate.prototype.push = function (value) {
  6953. _super.prototype.push.call(this, value);
  6954. if (!value.__smartArrayFlags) {
  6955. value.__smartArrayFlags = {};
  6956. }
  6957. value.__smartArrayFlags[this._id] = this._duplicateId;
  6958. };
  6959. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6960. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6961. return false;
  6962. }
  6963. this.push(value);
  6964. return true;
  6965. };
  6966. SmartArrayNoDuplicate.prototype.reset = function () {
  6967. _super.prototype.reset.call(this);
  6968. this._duplicateId++;
  6969. };
  6970. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6971. if (array.length === 0) {
  6972. return;
  6973. }
  6974. if (this.length + array.length > this.data.length) {
  6975. this.data.length = (this.length + array.length) * 2;
  6976. }
  6977. for (var index = 0; index < array.length; index++) {
  6978. var item = (array.data || array)[index];
  6979. this.pushNoDuplicate(item);
  6980. }
  6981. };
  6982. return SmartArrayNoDuplicate;
  6983. }(SmartArray));
  6984. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6985. })(BABYLON || (BABYLON = {}));
  6986. //# sourceMappingURL=babylon.smartArray.js.map
  6987. var BABYLON;
  6988. (function (BABYLON) {
  6989. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6990. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6991. var LoadFileError = /** @class */ (function (_super) {
  6992. __extends(LoadFileError, _super);
  6993. function LoadFileError(message, request) {
  6994. var _this = _super.call(this, message) || this;
  6995. _this.request = request;
  6996. _this.name = "LoadFileError";
  6997. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6998. return _this;
  6999. }
  7000. // Polyfill for Object.setPrototypeOf if necessary.
  7001. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7002. return LoadFileError;
  7003. }(Error));
  7004. BABYLON.LoadFileError = LoadFileError;
  7005. var RetryStrategy = /** @class */ (function () {
  7006. function RetryStrategy() {
  7007. }
  7008. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7009. if (maxRetries === void 0) { maxRetries = 3; }
  7010. if (baseInterval === void 0) { baseInterval = 500; }
  7011. return function (url, request, retryIndex) {
  7012. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7013. return -1;
  7014. }
  7015. return Math.pow(2, retryIndex) * baseInterval;
  7016. };
  7017. };
  7018. return RetryStrategy;
  7019. }());
  7020. BABYLON.RetryStrategy = RetryStrategy;
  7021. // Screenshots
  7022. var screenshotCanvas;
  7023. var cloneValue = function (source, destinationObject) {
  7024. if (!source)
  7025. return null;
  7026. if (source instanceof BABYLON.Mesh) {
  7027. return null;
  7028. }
  7029. if (source instanceof BABYLON.SubMesh) {
  7030. return source.clone(destinationObject);
  7031. }
  7032. else if (source.clone) {
  7033. return source.clone();
  7034. }
  7035. return null;
  7036. };
  7037. var Tools = /** @class */ (function () {
  7038. function Tools() {
  7039. }
  7040. /**
  7041. * Interpolates between a and b via alpha
  7042. * @param a The lower value (returned when alpha = 0)
  7043. * @param b The upper value (returned when alpha = 1)
  7044. * @param alpha The interpolation-factor
  7045. * @return The mixed value
  7046. */
  7047. Tools.Mix = function (a, b, alpha) {
  7048. return a * (1 - alpha) + b * alpha;
  7049. };
  7050. Tools.Instantiate = function (className) {
  7051. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7052. return Tools.RegisteredExternalClasses[className];
  7053. }
  7054. var arr = className.split(".");
  7055. var fn = (window || this);
  7056. for (var i = 0, len = arr.length; i < len; i++) {
  7057. fn = fn[arr[i]];
  7058. }
  7059. if (typeof fn !== "function") {
  7060. return null;
  7061. }
  7062. return fn;
  7063. };
  7064. /**
  7065. * Provides a slice function that will work even on IE
  7066. * @param data defines the array to slice
  7067. * @returns the new sliced array
  7068. */
  7069. Tools.Slice = function (data) {
  7070. if (data.slice) {
  7071. return data.slice();
  7072. }
  7073. return Array.prototype.slice.call(data);
  7074. };
  7075. Tools.SetImmediate = function (action) {
  7076. if (window.setImmediate) {
  7077. window.setImmediate(action);
  7078. }
  7079. else {
  7080. setTimeout(action, 1);
  7081. }
  7082. };
  7083. Tools.IsExponentOfTwo = function (value) {
  7084. var count = 1;
  7085. do {
  7086. count *= 2;
  7087. } while (count < value);
  7088. return count === value;
  7089. };
  7090. /**
  7091. * Find the next highest power of two.
  7092. * @param x Number to start search from.
  7093. * @return Next highest power of two.
  7094. */
  7095. Tools.CeilingPOT = function (x) {
  7096. x--;
  7097. x |= x >> 1;
  7098. x |= x >> 2;
  7099. x |= x >> 4;
  7100. x |= x >> 8;
  7101. x |= x >> 16;
  7102. x++;
  7103. return x;
  7104. };
  7105. /**
  7106. * Find the next lowest power of two.
  7107. * @param x Number to start search from.
  7108. * @return Next lowest power of two.
  7109. */
  7110. Tools.FloorPOT = function (x) {
  7111. x = x | (x >> 1);
  7112. x = x | (x >> 2);
  7113. x = x | (x >> 4);
  7114. x = x | (x >> 8);
  7115. x = x | (x >> 16);
  7116. return x - (x >> 1);
  7117. };
  7118. /**
  7119. * Find the nearest power of two.
  7120. * @param x Number to start search from.
  7121. * @return Next nearest power of two.
  7122. */
  7123. Tools.NearestPOT = function (x) {
  7124. var c = Tools.CeilingPOT(x);
  7125. var f = Tools.FloorPOT(x);
  7126. return (c - x) > (x - f) ? f : c;
  7127. };
  7128. Tools.GetExponentOfTwo = function (value, max, mode) {
  7129. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7130. var pot;
  7131. switch (mode) {
  7132. case BABYLON.Engine.SCALEMODE_FLOOR:
  7133. pot = Tools.FloorPOT(value);
  7134. break;
  7135. case BABYLON.Engine.SCALEMODE_NEAREST:
  7136. pot = Tools.NearestPOT(value);
  7137. break;
  7138. case BABYLON.Engine.SCALEMODE_CEILING:
  7139. default:
  7140. pot = Tools.CeilingPOT(value);
  7141. break;
  7142. }
  7143. return Math.min(pot, max);
  7144. };
  7145. Tools.GetFilename = function (path) {
  7146. var index = path.lastIndexOf("/");
  7147. if (index < 0)
  7148. return path;
  7149. return path.substring(index + 1);
  7150. };
  7151. /**
  7152. * Extracts the "folder" part of a path (everything before the filename).
  7153. * @param uri The URI to extract the info from
  7154. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7155. * @returns The "folder" part of the path
  7156. */
  7157. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7158. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7159. var index = uri.lastIndexOf("/");
  7160. if (index < 0) {
  7161. if (returnUnchangedIfNoSlash) {
  7162. return uri;
  7163. }
  7164. return "";
  7165. }
  7166. return uri.substring(0, index + 1);
  7167. };
  7168. Tools.GetDOMTextContent = function (element) {
  7169. var result = "";
  7170. var child = element.firstChild;
  7171. while (child) {
  7172. if (child.nodeType === 3) {
  7173. result += child.textContent;
  7174. }
  7175. child = child.nextSibling;
  7176. }
  7177. return result;
  7178. };
  7179. Tools.ToDegrees = function (angle) {
  7180. return angle * 180 / Math.PI;
  7181. };
  7182. Tools.ToRadians = function (angle) {
  7183. return angle * Math.PI / 180;
  7184. };
  7185. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7186. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7187. var output = "";
  7188. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7189. var i = 0;
  7190. var bytes = new Uint8Array(buffer);
  7191. while (i < bytes.length) {
  7192. chr1 = bytes[i++];
  7193. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7194. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7195. enc1 = chr1 >> 2;
  7196. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7197. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7198. enc4 = chr3 & 63;
  7199. if (isNaN(chr2)) {
  7200. enc3 = enc4 = 64;
  7201. }
  7202. else if (isNaN(chr3)) {
  7203. enc4 = 64;
  7204. }
  7205. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7206. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7207. }
  7208. return "data:image/png;base64," + output;
  7209. };
  7210. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7211. if (bias === void 0) { bias = null; }
  7212. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7213. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7214. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7215. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7216. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7217. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7218. }
  7219. if (bias) {
  7220. minimum.x -= minimum.x * bias.x + bias.y;
  7221. minimum.y -= minimum.y * bias.x + bias.y;
  7222. minimum.z -= minimum.z * bias.x + bias.y;
  7223. maximum.x += maximum.x * bias.x + bias.y;
  7224. maximum.y += maximum.y * bias.x + bias.y;
  7225. maximum.z += maximum.z * bias.x + bias.y;
  7226. }
  7227. return {
  7228. minimum: minimum,
  7229. maximum: maximum
  7230. };
  7231. };
  7232. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7233. if (bias === void 0) { bias = null; }
  7234. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7235. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7236. if (!stride) {
  7237. stride = 3;
  7238. }
  7239. for (var index = start; index < start + count; index++) {
  7240. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7241. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7242. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7243. }
  7244. if (bias) {
  7245. minimum.x -= minimum.x * bias.x + bias.y;
  7246. minimum.y -= minimum.y * bias.x + bias.y;
  7247. minimum.z -= minimum.z * bias.x + bias.y;
  7248. maximum.x += maximum.x * bias.x + bias.y;
  7249. maximum.y += maximum.y * bias.x + bias.y;
  7250. maximum.z += maximum.z * bias.x + bias.y;
  7251. }
  7252. return {
  7253. minimum: minimum,
  7254. maximum: maximum
  7255. };
  7256. };
  7257. Tools.Vector2ArrayFeeder = function (array) {
  7258. return function (index) {
  7259. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7260. var length = isFloatArray ? array.length / 2 : array.length;
  7261. if (index >= length) {
  7262. return null;
  7263. }
  7264. if (isFloatArray) {
  7265. var fa = array;
  7266. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7267. }
  7268. var a = array;
  7269. return a[index];
  7270. };
  7271. };
  7272. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7273. if (bias === void 0) { bias = null; }
  7274. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7275. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7276. var i = 0;
  7277. var cur = feeder(i++);
  7278. while (cur) {
  7279. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7280. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7281. cur = feeder(i++);
  7282. }
  7283. if (bias) {
  7284. minimum.x -= minimum.x * bias.x + bias.y;
  7285. minimum.y -= minimum.y * bias.x + bias.y;
  7286. maximum.x += maximum.x * bias.x + bias.y;
  7287. maximum.y += maximum.y * bias.x + bias.y;
  7288. }
  7289. return {
  7290. minimum: minimum,
  7291. maximum: maximum
  7292. };
  7293. };
  7294. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7295. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7296. return null;
  7297. return Array.isArray(obj) ? obj : [obj];
  7298. };
  7299. // Misc.
  7300. Tools.GetPointerPrefix = function () {
  7301. var eventPrefix = "pointer";
  7302. // Check if pointer events are supported
  7303. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7304. eventPrefix = "mouse";
  7305. }
  7306. return eventPrefix;
  7307. };
  7308. /**
  7309. * @param func - the function to be called
  7310. * @param requester - the object that will request the next frame. Falls back to window.
  7311. */
  7312. Tools.QueueNewFrame = function (func, requester) {
  7313. if (!Tools.IsWindowObjectExist()) {
  7314. return setTimeout(func, 16);
  7315. }
  7316. if (!requester) {
  7317. requester = window;
  7318. }
  7319. if (requester.requestAnimationFrame) {
  7320. return requester.requestAnimationFrame(func);
  7321. }
  7322. else if (requester.msRequestAnimationFrame) {
  7323. return requester.msRequestAnimationFrame(func);
  7324. }
  7325. else if (requester.webkitRequestAnimationFrame) {
  7326. return requester.webkitRequestAnimationFrame(func);
  7327. }
  7328. else if (requester.mozRequestAnimationFrame) {
  7329. return requester.mozRequestAnimationFrame(func);
  7330. }
  7331. else if (requester.oRequestAnimationFrame) {
  7332. return requester.oRequestAnimationFrame(func);
  7333. }
  7334. else {
  7335. return window.setTimeout(func, 16);
  7336. }
  7337. };
  7338. Tools.RequestFullscreen = function (element) {
  7339. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7340. if (!requestFunction)
  7341. return;
  7342. requestFunction.call(element);
  7343. };
  7344. Tools.ExitFullscreen = function () {
  7345. if (document.exitFullscreen) {
  7346. document.exitFullscreen();
  7347. }
  7348. else if (document.mozCancelFullScreen) {
  7349. document.mozCancelFullScreen();
  7350. }
  7351. else if (document.webkitCancelFullScreen) {
  7352. document.webkitCancelFullScreen();
  7353. }
  7354. else if (document.msCancelFullScreen) {
  7355. document.msCancelFullScreen();
  7356. }
  7357. };
  7358. Tools.SetCorsBehavior = function (url, element) {
  7359. if (url && url.indexOf("data:") === 0) {
  7360. return;
  7361. }
  7362. if (Tools.CorsBehavior) {
  7363. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7364. element.crossOrigin = Tools.CorsBehavior;
  7365. }
  7366. else {
  7367. var result = Tools.CorsBehavior(url);
  7368. if (result) {
  7369. element.crossOrigin = result;
  7370. }
  7371. }
  7372. }
  7373. };
  7374. // External files
  7375. Tools.CleanUrl = function (url) {
  7376. url = url.replace(/#/mg, "%23");
  7377. return url;
  7378. };
  7379. Tools.LoadImage = function (url, onLoad, onError, database) {
  7380. if (url instanceof ArrayBuffer) {
  7381. url = Tools.EncodeArrayBufferTobase64(url);
  7382. }
  7383. url = Tools.CleanUrl(url);
  7384. url = Tools.PreprocessUrl(url);
  7385. var img = new Image();
  7386. Tools.SetCorsBehavior(url, img);
  7387. img.onload = function () {
  7388. onLoad(img);
  7389. };
  7390. img.onerror = function (err) {
  7391. Tools.Error("Error while trying to load image: " + url);
  7392. if (onError) {
  7393. onError("Error while trying to load image: " + url, err);
  7394. }
  7395. };
  7396. var noIndexedDB = function () {
  7397. img.src = url;
  7398. };
  7399. var loadFromIndexedDB = function () {
  7400. if (database) {
  7401. database.loadImageFromDB(url, img);
  7402. }
  7403. };
  7404. //ANY database to do!
  7405. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7406. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7407. }
  7408. else {
  7409. if (url.indexOf("file:") !== -1) {
  7410. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7411. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7412. try {
  7413. var blobURL;
  7414. try {
  7415. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7416. }
  7417. catch (ex) {
  7418. // Chrome doesn't support oneTimeOnly parameter
  7419. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7420. }
  7421. img.src = blobURL;
  7422. }
  7423. catch (e) {
  7424. img.src = "";
  7425. }
  7426. return img;
  7427. }
  7428. }
  7429. noIndexedDB();
  7430. }
  7431. return img;
  7432. };
  7433. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7434. url = Tools.CleanUrl(url);
  7435. url = Tools.PreprocessUrl(url);
  7436. // If file and file input are set
  7437. if (url.indexOf("file:") !== -1) {
  7438. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7439. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7440. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7441. }
  7442. }
  7443. var loadUrl = Tools.BaseUrl + url;
  7444. var aborted = false;
  7445. var fileRequest = {
  7446. onCompleteObservable: new BABYLON.Observable(),
  7447. abort: function () { return aborted = true; },
  7448. };
  7449. var requestFile = function () {
  7450. var request = new XMLHttpRequest();
  7451. var retryHandle = null;
  7452. fileRequest.abort = function () {
  7453. aborted = true;
  7454. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7455. request.abort();
  7456. }
  7457. if (retryHandle !== null) {
  7458. clearTimeout(retryHandle);
  7459. retryHandle = null;
  7460. }
  7461. };
  7462. var retryLoop = function (retryIndex) {
  7463. request.open('GET', loadUrl, true);
  7464. if (useArrayBuffer) {
  7465. request.responseType = "arraybuffer";
  7466. }
  7467. if (onProgress) {
  7468. request.addEventListener("progress", onProgress);
  7469. }
  7470. var onLoadEnd = function () {
  7471. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7472. };
  7473. request.addEventListener("loadend", onLoadEnd);
  7474. var onReadyStateChange = function () {
  7475. if (aborted) {
  7476. return;
  7477. }
  7478. // In case of undefined state in some browsers.
  7479. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7480. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7481. request.removeEventListener("readystatechange", onReadyStateChange);
  7482. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7483. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7484. return;
  7485. }
  7486. var retryStrategy = Tools.DefaultRetryStrategy;
  7487. if (retryStrategy) {
  7488. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7489. if (waitTime !== -1) {
  7490. // Prevent the request from completing for retry.
  7491. request.removeEventListener("loadend", onLoadEnd);
  7492. request = new XMLHttpRequest();
  7493. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7494. return;
  7495. }
  7496. }
  7497. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7498. if (onError) {
  7499. onError(request, e);
  7500. }
  7501. else {
  7502. throw e;
  7503. }
  7504. }
  7505. };
  7506. request.addEventListener("readystatechange", onReadyStateChange);
  7507. request.send();
  7508. };
  7509. retryLoop(0);
  7510. };
  7511. // Caching all files
  7512. if (database && database.enableSceneOffline) {
  7513. var noIndexedDB_1 = function () {
  7514. if (!aborted) {
  7515. requestFile();
  7516. }
  7517. };
  7518. var loadFromIndexedDB = function () {
  7519. // TODO: database needs to support aborting and should return a IFileRequest
  7520. if (aborted) {
  7521. return;
  7522. }
  7523. if (database) {
  7524. database.loadFileFromDB(url, function (data) {
  7525. if (!aborted) {
  7526. onSuccess(data);
  7527. }
  7528. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7529. }, onProgress ? function (event) {
  7530. if (!aborted) {
  7531. onProgress(event);
  7532. }
  7533. } : undefined, noIndexedDB_1, useArrayBuffer);
  7534. }
  7535. };
  7536. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7537. }
  7538. else {
  7539. requestFile();
  7540. }
  7541. return fileRequest;
  7542. };
  7543. /**
  7544. * Load a script (identified by an url). When the url returns, the
  7545. * content of this file is added into a new script element, attached to the DOM (body element)
  7546. */
  7547. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7548. var head = document.getElementsByTagName('head')[0];
  7549. var script = document.createElement('script');
  7550. script.type = 'text/javascript';
  7551. script.src = scriptUrl;
  7552. script.onload = function () {
  7553. if (onSuccess) {
  7554. onSuccess();
  7555. }
  7556. };
  7557. script.onerror = function (e) {
  7558. if (onError) {
  7559. onError("Unable to load script", e);
  7560. }
  7561. };
  7562. head.appendChild(script);
  7563. };
  7564. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7565. var reader = new FileReader();
  7566. var request = {
  7567. onCompleteObservable: new BABYLON.Observable(),
  7568. abort: function () { return reader.abort(); },
  7569. };
  7570. reader.onloadend = function (e) {
  7571. request.onCompleteObservable.notifyObservers(request);
  7572. };
  7573. reader.onload = function (e) {
  7574. //target doesn't have result from ts 1.3
  7575. callback(e.target['result']);
  7576. };
  7577. reader.onprogress = progressCallback;
  7578. reader.readAsDataURL(fileToLoad);
  7579. return request;
  7580. };
  7581. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7582. var reader = new FileReader();
  7583. var request = {
  7584. onCompleteObservable: new BABYLON.Observable(),
  7585. abort: function () { return reader.abort(); },
  7586. };
  7587. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7588. reader.onerror = function (e) {
  7589. Tools.Log("Error while reading file: " + fileToLoad.name);
  7590. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7591. };
  7592. reader.onload = function (e) {
  7593. //target doesn't have result from ts 1.3
  7594. callback(e.target['result']);
  7595. };
  7596. if (progressCallBack) {
  7597. reader.onprogress = progressCallBack;
  7598. }
  7599. if (!useArrayBuffer) {
  7600. // Asynchronous read
  7601. reader.readAsText(fileToLoad);
  7602. }
  7603. else {
  7604. reader.readAsArrayBuffer(fileToLoad);
  7605. }
  7606. return request;
  7607. };
  7608. //returns a downloadable url to a file content.
  7609. Tools.FileAsURL = function (content) {
  7610. var fileBlob = new Blob([content]);
  7611. var url = window.URL || window.webkitURL;
  7612. var link = url.createObjectURL(fileBlob);
  7613. return link;
  7614. };
  7615. // Misc.
  7616. Tools.Format = function (value, decimals) {
  7617. if (decimals === void 0) { decimals = 2; }
  7618. return value.toFixed(decimals);
  7619. };
  7620. Tools.CheckExtends = function (v, min, max) {
  7621. if (v.x < min.x)
  7622. min.x = v.x;
  7623. if (v.y < min.y)
  7624. min.y = v.y;
  7625. if (v.z < min.z)
  7626. min.z = v.z;
  7627. if (v.x > max.x)
  7628. max.x = v.x;
  7629. if (v.y > max.y)
  7630. max.y = v.y;
  7631. if (v.z > max.z)
  7632. max.z = v.z;
  7633. };
  7634. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7635. for (var prop in source) {
  7636. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7637. continue;
  7638. }
  7639. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7640. continue;
  7641. }
  7642. var sourceValue = source[prop];
  7643. var typeOfSourceValue = typeof sourceValue;
  7644. if (typeOfSourceValue === "function") {
  7645. continue;
  7646. }
  7647. if (typeOfSourceValue === "object") {
  7648. if (sourceValue instanceof Array) {
  7649. destination[prop] = [];
  7650. if (sourceValue.length > 0) {
  7651. if (typeof sourceValue[0] == "object") {
  7652. for (var index = 0; index < sourceValue.length; index++) {
  7653. var clonedValue = cloneValue(sourceValue[index], destination);
  7654. if (destination[prop].indexOf(clonedValue) === -1) {
  7655. destination[prop].push(clonedValue);
  7656. }
  7657. }
  7658. }
  7659. else {
  7660. destination[prop] = sourceValue.slice(0);
  7661. }
  7662. }
  7663. }
  7664. else {
  7665. destination[prop] = cloneValue(sourceValue, destination);
  7666. }
  7667. }
  7668. else {
  7669. destination[prop] = sourceValue;
  7670. }
  7671. }
  7672. };
  7673. Tools.IsEmpty = function (obj) {
  7674. for (var i in obj) {
  7675. if (obj.hasOwnProperty(i)) {
  7676. return false;
  7677. }
  7678. }
  7679. return true;
  7680. };
  7681. Tools.RegisterTopRootEvents = function (events) {
  7682. for (var index = 0; index < events.length; index++) {
  7683. var event = events[index];
  7684. window.addEventListener(event.name, event.handler, false);
  7685. try {
  7686. if (window.parent) {
  7687. window.parent.addEventListener(event.name, event.handler, false);
  7688. }
  7689. }
  7690. catch (e) {
  7691. // Silently fails...
  7692. }
  7693. }
  7694. };
  7695. Tools.UnregisterTopRootEvents = function (events) {
  7696. for (var index = 0; index < events.length; index++) {
  7697. var event = events[index];
  7698. window.removeEventListener(event.name, event.handler);
  7699. try {
  7700. if (window.parent) {
  7701. window.parent.removeEventListener(event.name, event.handler);
  7702. }
  7703. }
  7704. catch (e) {
  7705. // Silently fails...
  7706. }
  7707. }
  7708. };
  7709. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7710. if (mimeType === void 0) { mimeType = "image/png"; }
  7711. // Read the contents of the framebuffer
  7712. var numberOfChannelsByLine = width * 4;
  7713. var halfHeight = height / 2;
  7714. //Reading datas from WebGL
  7715. var data = engine.readPixels(0, 0, width, height);
  7716. //To flip image on Y axis.
  7717. for (var i = 0; i < halfHeight; i++) {
  7718. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7719. var currentCell = j + i * numberOfChannelsByLine;
  7720. var targetLine = height - i - 1;
  7721. var targetCell = j + targetLine * numberOfChannelsByLine;
  7722. var temp = data[currentCell];
  7723. data[currentCell] = data[targetCell];
  7724. data[targetCell] = temp;
  7725. }
  7726. }
  7727. // Create a 2D canvas to store the result
  7728. if (!screenshotCanvas) {
  7729. screenshotCanvas = document.createElement('canvas');
  7730. }
  7731. screenshotCanvas.width = width;
  7732. screenshotCanvas.height = height;
  7733. var context = screenshotCanvas.getContext('2d');
  7734. if (context) {
  7735. // Copy the pixels to a 2D canvas
  7736. var imageData = context.createImageData(width, height);
  7737. var castData = (imageData.data);
  7738. castData.set(data);
  7739. context.putImageData(imageData, 0, 0);
  7740. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7741. }
  7742. };
  7743. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7744. if (mimeType === void 0) { mimeType = "image/png"; }
  7745. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7746. if (successCallback) {
  7747. successCallback(base64Image);
  7748. }
  7749. else {
  7750. // We need HTMLCanvasElement.toBlob for HD screenshots
  7751. if (!screenshotCanvas.toBlob) {
  7752. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7753. screenshotCanvas.toBlob = function (callback, type, quality) {
  7754. var _this = this;
  7755. setTimeout(function () {
  7756. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7757. for (var i = 0; i < len; i++) {
  7758. arr[i] = binStr.charCodeAt(i);
  7759. }
  7760. callback(new Blob([arr], { type: type || 'image/png' }));
  7761. });
  7762. };
  7763. }
  7764. screenshotCanvas.toBlob(function (blob) {
  7765. var url = URL.createObjectURL(blob);
  7766. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7767. if (("download" in document.createElement("a"))) {
  7768. var a = window.document.createElement("a");
  7769. a.href = url;
  7770. if (fileName) {
  7771. a.setAttribute("download", fileName);
  7772. }
  7773. else {
  7774. var date = new Date();
  7775. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7776. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7777. }
  7778. window.document.body.appendChild(a);
  7779. a.addEventListener("click", function () {
  7780. if (a.parentElement) {
  7781. a.parentElement.removeChild(a);
  7782. }
  7783. });
  7784. a.click();
  7785. }
  7786. else {
  7787. var newWindow = window.open("");
  7788. if (!newWindow)
  7789. return;
  7790. var img = newWindow.document.createElement("img");
  7791. img.onload = function () {
  7792. // no longer need to read the blob so it's revoked
  7793. URL.revokeObjectURL(url);
  7794. };
  7795. img.src = url;
  7796. newWindow.document.body.appendChild(img);
  7797. }
  7798. });
  7799. }
  7800. };
  7801. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7802. if (mimeType === void 0) { mimeType = "image/png"; }
  7803. var width;
  7804. var height;
  7805. // If a precision value is specified
  7806. if (size.precision) {
  7807. width = Math.round(engine.getRenderWidth() * size.precision);
  7808. height = Math.round(width / engine.getAspectRatio(camera));
  7809. }
  7810. else if (size.width && size.height) {
  7811. width = size.width;
  7812. height = size.height;
  7813. }
  7814. else if (size.width && !size.height) {
  7815. width = size.width;
  7816. height = Math.round(width / engine.getAspectRatio(camera));
  7817. }
  7818. else if (size.height && !size.width) {
  7819. height = size.height;
  7820. width = Math.round(height * engine.getAspectRatio(camera));
  7821. }
  7822. else if (!isNaN(size)) {
  7823. height = size;
  7824. width = size;
  7825. }
  7826. else {
  7827. Tools.Error("Invalid 'size' parameter !");
  7828. return;
  7829. }
  7830. if (!screenshotCanvas) {
  7831. screenshotCanvas = document.createElement('canvas');
  7832. }
  7833. screenshotCanvas.width = width;
  7834. screenshotCanvas.height = height;
  7835. var renderContext = screenshotCanvas.getContext("2d");
  7836. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7837. var newWidth = width;
  7838. var newHeight = newWidth / ratio;
  7839. if (newHeight > height) {
  7840. newHeight = height;
  7841. newWidth = newHeight * ratio;
  7842. }
  7843. var offsetX = Math.max(0, width - newWidth) / 2;
  7844. var offsetY = Math.max(0, height - newHeight) / 2;
  7845. var renderingCanvas = engine.getRenderingCanvas();
  7846. if (renderContext && renderingCanvas) {
  7847. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7848. }
  7849. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7850. };
  7851. /**
  7852. * Generates an image screenshot from the specified camera.
  7853. *
  7854. * @param engine The engine to use for rendering
  7855. * @param camera The camera to use for rendering
  7856. * @param size This parameter can be set to a single number or to an object with the
  7857. * following (optional) properties: precision, width, height. If a single number is passed,
  7858. * it will be used for both width and height. If an object is passed, the screenshot size
  7859. * will be derived from the parameters. The precision property is a multiplier allowing
  7860. * rendering at a higher or lower resolution.
  7861. * @param successCallback The callback receives a single parameter which contains the
  7862. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7863. * src parameter of an <img> to display it.
  7864. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7865. * Check your browser for supported MIME types.
  7866. * @param samples Texture samples (default: 1)
  7867. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7868. * @param fileName A name for for the downloaded file.
  7869. * @constructor
  7870. */
  7871. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7872. if (mimeType === void 0) { mimeType = "image/png"; }
  7873. if (samples === void 0) { samples = 1; }
  7874. if (antialiasing === void 0) { antialiasing = false; }
  7875. var width;
  7876. var height;
  7877. //If a precision value is specified
  7878. if (size.precision) {
  7879. width = Math.round(engine.getRenderWidth() * size.precision);
  7880. height = Math.round(width / engine.getAspectRatio(camera));
  7881. size = { width: width, height: height };
  7882. }
  7883. else if (size.width && size.height) {
  7884. width = size.width;
  7885. height = size.height;
  7886. }
  7887. else if (size.width && !size.height) {
  7888. width = size.width;
  7889. height = Math.round(width / engine.getAspectRatio(camera));
  7890. size = { width: width, height: height };
  7891. }
  7892. else if (size.height && !size.width) {
  7893. height = size.height;
  7894. width = Math.round(height * engine.getAspectRatio(camera));
  7895. size = { width: width, height: height };
  7896. }
  7897. else if (!isNaN(size)) {
  7898. height = size;
  7899. width = size;
  7900. }
  7901. else {
  7902. Tools.Error("Invalid 'size' parameter !");
  7903. return;
  7904. }
  7905. var scene = camera.getScene();
  7906. var previousCamera = null;
  7907. if (scene.activeCamera !== camera) {
  7908. previousCamera = scene.activeCamera;
  7909. scene.activeCamera = camera;
  7910. }
  7911. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7912. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7913. texture.renderList = null;
  7914. texture.samples = samples;
  7915. if (antialiasing) {
  7916. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7917. }
  7918. texture.onAfterRenderObservable.add(function () {
  7919. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7920. });
  7921. scene.incrementRenderId();
  7922. scene.resetCachedMaterial();
  7923. texture.render(true);
  7924. texture.dispose();
  7925. if (previousCamera) {
  7926. scene.activeCamera = previousCamera;
  7927. }
  7928. camera.getProjectionMatrix(true); // Force cache refresh;
  7929. };
  7930. // XHR response validator for local file scenario
  7931. Tools.ValidateXHRData = function (xhr, dataType) {
  7932. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7933. if (dataType === void 0) { dataType = 7; }
  7934. try {
  7935. if (dataType & 1) {
  7936. if (xhr.responseText && xhr.responseText.length > 0) {
  7937. return true;
  7938. }
  7939. else if (dataType === 1) {
  7940. return false;
  7941. }
  7942. }
  7943. if (dataType & 2) {
  7944. // Check header width and height since there is no "TGA" magic number
  7945. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7946. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7947. return true;
  7948. }
  7949. else if (dataType === 2) {
  7950. return false;
  7951. }
  7952. }
  7953. if (dataType & 4) {
  7954. // Check for the "DDS" magic number
  7955. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7956. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7957. return true;
  7958. }
  7959. else {
  7960. return false;
  7961. }
  7962. }
  7963. }
  7964. catch (e) {
  7965. // Global protection
  7966. }
  7967. return false;
  7968. };
  7969. /**
  7970. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7971. * Be aware Math.random() could cause collisions, but:
  7972. * "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"
  7973. */
  7974. Tools.RandomId = function () {
  7975. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7976. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7977. return v.toString(16);
  7978. });
  7979. };
  7980. /**
  7981. * Test if the given uri is a base64 string.
  7982. * @param uri The uri to test
  7983. * @return True if the uri is a base64 string or false otherwise.
  7984. */
  7985. Tools.IsBase64 = function (uri) {
  7986. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7987. };
  7988. /**
  7989. * Decode the given base64 uri.
  7990. * @param uri The uri to decode
  7991. * @return The decoded base64 data.
  7992. */
  7993. Tools.DecodeBase64 = function (uri) {
  7994. var decodedString = atob(uri.split(",")[1]);
  7995. var bufferLength = decodedString.length;
  7996. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7997. for (var i = 0; i < bufferLength; i++) {
  7998. bufferView[i] = decodedString.charCodeAt(i);
  7999. }
  8000. return bufferView.buffer;
  8001. };
  8002. Object.defineProperty(Tools, "NoneLogLevel", {
  8003. get: function () {
  8004. return Tools._NoneLogLevel;
  8005. },
  8006. enumerable: true,
  8007. configurable: true
  8008. });
  8009. Object.defineProperty(Tools, "MessageLogLevel", {
  8010. get: function () {
  8011. return Tools._MessageLogLevel;
  8012. },
  8013. enumerable: true,
  8014. configurable: true
  8015. });
  8016. Object.defineProperty(Tools, "WarningLogLevel", {
  8017. get: function () {
  8018. return Tools._WarningLogLevel;
  8019. },
  8020. enumerable: true,
  8021. configurable: true
  8022. });
  8023. Object.defineProperty(Tools, "ErrorLogLevel", {
  8024. get: function () {
  8025. return Tools._ErrorLogLevel;
  8026. },
  8027. enumerable: true,
  8028. configurable: true
  8029. });
  8030. Object.defineProperty(Tools, "AllLogLevel", {
  8031. get: function () {
  8032. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8033. },
  8034. enumerable: true,
  8035. configurable: true
  8036. });
  8037. Tools._AddLogEntry = function (entry) {
  8038. Tools._LogCache = entry + Tools._LogCache;
  8039. if (Tools.OnNewCacheEntry) {
  8040. Tools.OnNewCacheEntry(entry);
  8041. }
  8042. };
  8043. Tools._FormatMessage = function (message) {
  8044. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8045. var date = new Date();
  8046. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8047. };
  8048. Tools._LogDisabled = function (message) {
  8049. // nothing to do
  8050. };
  8051. Tools._LogEnabled = function (message) {
  8052. var formattedMessage = Tools._FormatMessage(message);
  8053. console.log("BJS - " + formattedMessage);
  8054. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8055. Tools._AddLogEntry(entry);
  8056. };
  8057. Tools._WarnDisabled = function (message) {
  8058. // nothing to do
  8059. };
  8060. Tools._WarnEnabled = function (message) {
  8061. var formattedMessage = Tools._FormatMessage(message);
  8062. console.warn("BJS - " + formattedMessage);
  8063. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8064. Tools._AddLogEntry(entry);
  8065. };
  8066. Tools._ErrorDisabled = function (message) {
  8067. // nothing to do
  8068. };
  8069. Tools._ErrorEnabled = function (message) {
  8070. Tools.errorsCount++;
  8071. var formattedMessage = Tools._FormatMessage(message);
  8072. console.error("BJS - " + formattedMessage);
  8073. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8074. Tools._AddLogEntry(entry);
  8075. };
  8076. Object.defineProperty(Tools, "LogCache", {
  8077. get: function () {
  8078. return Tools._LogCache;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Tools.ClearLogCache = function () {
  8084. Tools._LogCache = "";
  8085. Tools.errorsCount = 0;
  8086. };
  8087. Object.defineProperty(Tools, "LogLevels", {
  8088. set: function (level) {
  8089. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8090. Tools.Log = Tools._LogEnabled;
  8091. }
  8092. else {
  8093. Tools.Log = Tools._LogDisabled;
  8094. }
  8095. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8096. Tools.Warn = Tools._WarnEnabled;
  8097. }
  8098. else {
  8099. Tools.Warn = Tools._WarnDisabled;
  8100. }
  8101. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8102. Tools.Error = Tools._ErrorEnabled;
  8103. }
  8104. else {
  8105. Tools.Error = Tools._ErrorDisabled;
  8106. }
  8107. },
  8108. enumerable: true,
  8109. configurable: true
  8110. });
  8111. Tools.IsWindowObjectExist = function () {
  8112. return (typeof window) !== "undefined";
  8113. };
  8114. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8115. get: function () {
  8116. return Tools._PerformanceNoneLogLevel;
  8117. },
  8118. enumerable: true,
  8119. configurable: true
  8120. });
  8121. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8122. get: function () {
  8123. return Tools._PerformanceUserMarkLogLevel;
  8124. },
  8125. enumerable: true,
  8126. configurable: true
  8127. });
  8128. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8129. get: function () {
  8130. return Tools._PerformanceConsoleLogLevel;
  8131. },
  8132. enumerable: true,
  8133. configurable: true
  8134. });
  8135. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8136. set: function (level) {
  8137. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8138. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8139. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8140. return;
  8141. }
  8142. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8143. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8144. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8145. return;
  8146. }
  8147. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8148. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8149. },
  8150. enumerable: true,
  8151. configurable: true
  8152. });
  8153. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8154. };
  8155. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8156. };
  8157. Tools._StartUserMark = function (counterName, condition) {
  8158. if (condition === void 0) { condition = true; }
  8159. if (!Tools._performance) {
  8160. if (!Tools.IsWindowObjectExist()) {
  8161. return;
  8162. }
  8163. Tools._performance = window.performance;
  8164. }
  8165. if (!condition || !Tools._performance.mark) {
  8166. return;
  8167. }
  8168. Tools._performance.mark(counterName + "-Begin");
  8169. };
  8170. Tools._EndUserMark = function (counterName, condition) {
  8171. if (condition === void 0) { condition = true; }
  8172. if (!condition || !Tools._performance.mark) {
  8173. return;
  8174. }
  8175. Tools._performance.mark(counterName + "-End");
  8176. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8177. };
  8178. Tools._StartPerformanceConsole = function (counterName, condition) {
  8179. if (condition === void 0) { condition = true; }
  8180. if (!condition) {
  8181. return;
  8182. }
  8183. Tools._StartUserMark(counterName, condition);
  8184. if (console.time) {
  8185. console.time(counterName);
  8186. }
  8187. };
  8188. Tools._EndPerformanceConsole = function (counterName, condition) {
  8189. if (condition === void 0) { condition = true; }
  8190. if (!condition) {
  8191. return;
  8192. }
  8193. Tools._EndUserMark(counterName, condition);
  8194. if (console.time) {
  8195. console.timeEnd(counterName);
  8196. }
  8197. };
  8198. Object.defineProperty(Tools, "Now", {
  8199. get: function () {
  8200. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8201. return window.performance.now();
  8202. }
  8203. return new Date().getTime();
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. /**
  8209. * This method will return the name of the class used to create the instance of the given object.
  8210. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8211. * @param object the object to get the class name from
  8212. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8213. */
  8214. Tools.GetClassName = function (object, isType) {
  8215. if (isType === void 0) { isType = false; }
  8216. var name = null;
  8217. if (!isType && object.getClassName) {
  8218. name = object.getClassName();
  8219. }
  8220. else {
  8221. if (object instanceof Object) {
  8222. var classObj = isType ? object : Object.getPrototypeOf(object);
  8223. name = classObj.constructor["__bjsclassName__"];
  8224. }
  8225. if (!name) {
  8226. name = typeof object;
  8227. }
  8228. }
  8229. return name;
  8230. };
  8231. Tools.First = function (array, predicate) {
  8232. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8233. var el = array_1[_i];
  8234. if (predicate(el)) {
  8235. return el;
  8236. }
  8237. }
  8238. return null;
  8239. };
  8240. /**
  8241. * This method will return the name of the full name of the class, including its owning module (if any).
  8242. * 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).
  8243. * @param object the object to get the class name from
  8244. * @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.
  8245. */
  8246. Tools.getFullClassName = function (object, isType) {
  8247. if (isType === void 0) { isType = false; }
  8248. var className = null;
  8249. var moduleName = null;
  8250. if (!isType && object.getClassName) {
  8251. className = object.getClassName();
  8252. }
  8253. else {
  8254. if (object instanceof Object) {
  8255. var classObj = isType ? object : Object.getPrototypeOf(object);
  8256. className = classObj.constructor["__bjsclassName__"];
  8257. moduleName = classObj.constructor["__bjsmoduleName__"];
  8258. }
  8259. if (!className) {
  8260. className = typeof object;
  8261. }
  8262. }
  8263. if (!className) {
  8264. return null;
  8265. }
  8266. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8267. };
  8268. /**
  8269. * 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.
  8270. * @param array
  8271. */
  8272. Tools.arrayOrStringFeeder = function (array) {
  8273. return function (index) {
  8274. if (index >= array.length) {
  8275. return null;
  8276. }
  8277. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8278. if (val && val.getHashCode) {
  8279. val = val.getHashCode();
  8280. }
  8281. if (typeof val === "string") {
  8282. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8283. }
  8284. return val;
  8285. };
  8286. };
  8287. /**
  8288. * Compute the hashCode of a stream of number
  8289. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8290. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8291. * @return the hash code computed
  8292. */
  8293. Tools.hashCodeFromStream = function (feeder) {
  8294. // Based from here: http://stackoverflow.com/a/7616484/802124
  8295. var hash = 0;
  8296. var index = 0;
  8297. var chr = feeder(index++);
  8298. while (chr != null) {
  8299. hash = ((hash << 5) - hash) + chr;
  8300. hash |= 0; // Convert to 32bit integer
  8301. chr = feeder(index++);
  8302. }
  8303. return hash;
  8304. };
  8305. Tools.BaseUrl = "";
  8306. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8307. /**
  8308. * Default behaviour for cors in the application.
  8309. * It can be a string if the expected behavior is identical in the entire app.
  8310. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8311. */
  8312. Tools.CorsBehavior = "anonymous";
  8313. Tools.UseFallbackTexture = true;
  8314. /**
  8315. * Use this object to register external classes like custom textures or material
  8316. * to allow the laoders to instantiate them
  8317. */
  8318. Tools.RegisteredExternalClasses = {};
  8319. // Used in case of a texture loading problem
  8320. 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";
  8321. Tools.PreprocessUrl = function (url) {
  8322. return url;
  8323. };
  8324. // Logs
  8325. Tools._NoneLogLevel = 0;
  8326. Tools._MessageLogLevel = 1;
  8327. Tools._WarningLogLevel = 2;
  8328. Tools._ErrorLogLevel = 4;
  8329. Tools._LogCache = "";
  8330. Tools.errorsCount = 0;
  8331. Tools.Log = Tools._LogEnabled;
  8332. Tools.Warn = Tools._WarnEnabled;
  8333. Tools.Error = Tools._ErrorEnabled;
  8334. // Performances
  8335. Tools._PerformanceNoneLogLevel = 0;
  8336. Tools._PerformanceUserMarkLogLevel = 1;
  8337. Tools._PerformanceConsoleLogLevel = 2;
  8338. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8339. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8340. return Tools;
  8341. }());
  8342. BABYLON.Tools = Tools;
  8343. /**
  8344. * This class is used to track a performance counter which is number based.
  8345. * The user has access to many properties which give statistics of different nature
  8346. *
  8347. * The implementer can track two kinds of Performance Counter: time and count
  8348. * 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.
  8349. * 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.
  8350. */
  8351. var PerfCounter = /** @class */ (function () {
  8352. function PerfCounter() {
  8353. this._startMonitoringTime = 0;
  8354. this._min = 0;
  8355. this._max = 0;
  8356. this._average = 0;
  8357. this._lastSecAverage = 0;
  8358. this._current = 0;
  8359. this._totalValueCount = 0;
  8360. this._totalAccumulated = 0;
  8361. this._lastSecAccumulated = 0;
  8362. this._lastSecTime = 0;
  8363. this._lastSecValueCount = 0;
  8364. }
  8365. Object.defineProperty(PerfCounter.prototype, "min", {
  8366. /**
  8367. * Returns the smallest value ever
  8368. */
  8369. get: function () {
  8370. return this._min;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. Object.defineProperty(PerfCounter.prototype, "max", {
  8376. /**
  8377. * Returns the biggest value ever
  8378. */
  8379. get: function () {
  8380. return this._max;
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. Object.defineProperty(PerfCounter.prototype, "average", {
  8386. /**
  8387. * Returns the average value since the performance counter is running
  8388. */
  8389. get: function () {
  8390. return this._average;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8396. /**
  8397. * Returns the average value of the last second the counter was monitored
  8398. */
  8399. get: function () {
  8400. return this._lastSecAverage;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(PerfCounter.prototype, "current", {
  8406. /**
  8407. * Returns the current value
  8408. */
  8409. get: function () {
  8410. return this._current;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(PerfCounter.prototype, "total", {
  8416. get: function () {
  8417. return this._totalAccumulated;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(PerfCounter.prototype, "count", {
  8423. get: function () {
  8424. return this._totalValueCount;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. /**
  8430. * Call this method to start monitoring a new frame.
  8431. * 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.
  8432. */
  8433. PerfCounter.prototype.fetchNewFrame = function () {
  8434. this._totalValueCount++;
  8435. this._current = 0;
  8436. this._lastSecValueCount++;
  8437. };
  8438. /**
  8439. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8440. * @param newCount the count value to add to the monitored count
  8441. * @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.
  8442. */
  8443. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8444. if (!PerfCounter.Enabled) {
  8445. return;
  8446. }
  8447. this._current += newCount;
  8448. if (fetchResult) {
  8449. this._fetchResult();
  8450. }
  8451. };
  8452. /**
  8453. * Start monitoring this performance counter
  8454. */
  8455. PerfCounter.prototype.beginMonitoring = function () {
  8456. if (!PerfCounter.Enabled) {
  8457. return;
  8458. }
  8459. this._startMonitoringTime = Tools.Now;
  8460. };
  8461. /**
  8462. * Compute the time lapsed since the previous beginMonitoring() call.
  8463. * @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
  8464. */
  8465. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8466. if (newFrame === void 0) { newFrame = true; }
  8467. if (!PerfCounter.Enabled) {
  8468. return;
  8469. }
  8470. if (newFrame) {
  8471. this.fetchNewFrame();
  8472. }
  8473. var currentTime = Tools.Now;
  8474. this._current = currentTime - this._startMonitoringTime;
  8475. if (newFrame) {
  8476. this._fetchResult();
  8477. }
  8478. };
  8479. PerfCounter.prototype._fetchResult = function () {
  8480. this._totalAccumulated += this._current;
  8481. this._lastSecAccumulated += this._current;
  8482. // Min/Max update
  8483. this._min = Math.min(this._min, this._current);
  8484. this._max = Math.max(this._max, this._current);
  8485. this._average = this._totalAccumulated / this._totalValueCount;
  8486. // Reset last sec?
  8487. var now = Tools.Now;
  8488. if ((now - this._lastSecTime) > 1000) {
  8489. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8490. this._lastSecTime = now;
  8491. this._lastSecAccumulated = 0;
  8492. this._lastSecValueCount = 0;
  8493. }
  8494. };
  8495. PerfCounter.Enabled = true;
  8496. return PerfCounter;
  8497. }());
  8498. BABYLON.PerfCounter = PerfCounter;
  8499. /**
  8500. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8501. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8502. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8503. * @param name The name of the class, case should be preserved
  8504. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8505. */
  8506. function className(name, module) {
  8507. return function (target) {
  8508. target["__bjsclassName__"] = name;
  8509. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8510. };
  8511. }
  8512. BABYLON.className = className;
  8513. /**
  8514. * An implementation of a loop for asynchronous functions.
  8515. */
  8516. var AsyncLoop = /** @class */ (function () {
  8517. /**
  8518. * Constroctor.
  8519. * @param iterations the number of iterations.
  8520. * @param _fn the function to run each iteration
  8521. * @param _successCallback the callback that will be called upon succesful execution
  8522. * @param offset starting offset.
  8523. */
  8524. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8525. if (offset === void 0) { offset = 0; }
  8526. this.iterations = iterations;
  8527. this._fn = _fn;
  8528. this._successCallback = _successCallback;
  8529. this.index = offset - 1;
  8530. this._done = false;
  8531. }
  8532. /**
  8533. * Execute the next iteration. Must be called after the last iteration was finished.
  8534. */
  8535. AsyncLoop.prototype.executeNext = function () {
  8536. if (!this._done) {
  8537. if (this.index + 1 < this.iterations) {
  8538. ++this.index;
  8539. this._fn(this);
  8540. }
  8541. else {
  8542. this.breakLoop();
  8543. }
  8544. }
  8545. };
  8546. /**
  8547. * Break the loop and run the success callback.
  8548. */
  8549. AsyncLoop.prototype.breakLoop = function () {
  8550. this._done = true;
  8551. this._successCallback();
  8552. };
  8553. /**
  8554. * Helper function
  8555. */
  8556. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8557. if (offset === void 0) { offset = 0; }
  8558. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8559. loop.executeNext();
  8560. return loop;
  8561. };
  8562. /**
  8563. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8564. * @param iterations total number of iterations
  8565. * @param syncedIterations number of synchronous iterations in each async iteration.
  8566. * @param fn the function to call each iteration.
  8567. * @param callback a success call back that will be called when iterating stops.
  8568. * @param breakFunction a break condition (optional)
  8569. * @param timeout timeout settings for the setTimeout function. default - 0.
  8570. * @constructor
  8571. */
  8572. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8573. if (timeout === void 0) { timeout = 0; }
  8574. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8575. if (breakFunction && breakFunction())
  8576. loop.breakLoop();
  8577. else {
  8578. setTimeout(function () {
  8579. for (var i = 0; i < syncedIterations; ++i) {
  8580. var iteration = (loop.index * syncedIterations) + i;
  8581. if (iteration >= iterations)
  8582. break;
  8583. fn(iteration);
  8584. if (breakFunction && breakFunction()) {
  8585. loop.breakLoop();
  8586. break;
  8587. }
  8588. }
  8589. loop.executeNext();
  8590. }, timeout);
  8591. }
  8592. }, callback);
  8593. };
  8594. return AsyncLoop;
  8595. }());
  8596. BABYLON.AsyncLoop = AsyncLoop;
  8597. })(BABYLON || (BABYLON = {}));
  8598. //# sourceMappingURL=babylon.tools.js.map
  8599. var BABYLON;
  8600. (function (BABYLON) {
  8601. var PromiseStates;
  8602. (function (PromiseStates) {
  8603. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8604. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8605. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8606. })(PromiseStates || (PromiseStates = {}));
  8607. var FulFillmentAgregator = /** @class */ (function () {
  8608. function FulFillmentAgregator() {
  8609. this.count = 0;
  8610. this.target = 0;
  8611. this.results = [];
  8612. }
  8613. return FulFillmentAgregator;
  8614. }());
  8615. var InternalPromise = /** @class */ (function () {
  8616. function InternalPromise(resolver) {
  8617. var _this = this;
  8618. this._state = PromiseStates.Pending;
  8619. this._children = new Array();
  8620. this._rejectWasConsumed = false;
  8621. if (!resolver) {
  8622. return;
  8623. }
  8624. try {
  8625. resolver(function (value) {
  8626. _this._resolve(value);
  8627. }, function (reason) {
  8628. _this._reject(reason);
  8629. });
  8630. }
  8631. catch (e) {
  8632. this._reject(e.message);
  8633. }
  8634. }
  8635. Object.defineProperty(InternalPromise.prototype, "state", {
  8636. get: function () {
  8637. return this._state;
  8638. },
  8639. enumerable: true,
  8640. configurable: true
  8641. });
  8642. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8643. get: function () {
  8644. return this._state === PromiseStates.Fulfilled;
  8645. },
  8646. enumerable: true,
  8647. configurable: true
  8648. });
  8649. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8650. get: function () {
  8651. return this._state === PromiseStates.Rejected;
  8652. },
  8653. enumerable: true,
  8654. configurable: true
  8655. });
  8656. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8657. get: function () {
  8658. return this._state === PromiseStates.Pending;
  8659. },
  8660. enumerable: true,
  8661. configurable: true
  8662. });
  8663. InternalPromise.prototype.value = function () {
  8664. if (!this.isFulfilled) {
  8665. throw new Error("Promise is not fulfilled");
  8666. }
  8667. return this._result;
  8668. };
  8669. InternalPromise.prototype.reason = function () {
  8670. if (!this.isRejected) {
  8671. throw new Error("Promise is not rejected");
  8672. }
  8673. return this._reason;
  8674. };
  8675. InternalPromise.prototype.catch = function (onRejected) {
  8676. return this.then(undefined, onRejected);
  8677. };
  8678. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8679. var newPromise = new InternalPromise();
  8680. newPromise._onFulfilled = onFulfilled;
  8681. newPromise._onRejected = onRejected;
  8682. // Composition
  8683. this._children.push(newPromise);
  8684. if (this._state !== PromiseStates.Pending) {
  8685. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8686. var returnedValue = newPromise._resolve(this._result);
  8687. if (returnedValue !== undefined && returnedValue !== null) {
  8688. if (returnedValue._state !== undefined) {
  8689. var returnedPromise = returnedValue;
  8690. newPromise._children.push(returnedPromise);
  8691. newPromise = returnedPromise;
  8692. }
  8693. else {
  8694. newPromise._result = returnedValue;
  8695. }
  8696. }
  8697. }
  8698. else {
  8699. newPromise._reject(this._reason);
  8700. }
  8701. }
  8702. return newPromise;
  8703. };
  8704. InternalPromise.prototype._moveChildren = function (children) {
  8705. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  8706. if (this.isFulfilled) {
  8707. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  8708. var child = _b[_i];
  8709. child._resolve(this._result);
  8710. }
  8711. }
  8712. else if (this.isRejected) {
  8713. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  8714. var child = _d[_c];
  8715. child._reject(this._reason);
  8716. }
  8717. }
  8718. var _a;
  8719. };
  8720. InternalPromise.prototype._resolve = function (value) {
  8721. try {
  8722. this._state = PromiseStates.Fulfilled;
  8723. this._result = value;
  8724. var returnedValue = null;
  8725. if (this._onFulfilled) {
  8726. returnedValue = this._onFulfilled(value);
  8727. }
  8728. if (returnedValue !== undefined && returnedValue !== null) {
  8729. if (returnedValue._state !== undefined) {
  8730. // Transmit children
  8731. var returnedPromise = returnedValue;
  8732. returnedPromise._moveChildren(this._children);
  8733. }
  8734. else {
  8735. value = returnedValue;
  8736. }
  8737. }
  8738. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8739. var child = _a[_i];
  8740. child._resolve(value);
  8741. }
  8742. return returnedValue;
  8743. }
  8744. catch (e) {
  8745. this._reject(e.message);
  8746. }
  8747. return null;
  8748. };
  8749. InternalPromise.prototype._reject = function (reason) {
  8750. this._state = PromiseStates.Rejected;
  8751. this._reason = reason;
  8752. if (this._onRejected) {
  8753. this._onRejected(reason);
  8754. this._rejectWasConsumed = true;
  8755. }
  8756. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8757. var child = _a[_i];
  8758. if (this._rejectWasConsumed) {
  8759. child._resolve(null);
  8760. }
  8761. else {
  8762. child._reject(reason);
  8763. }
  8764. }
  8765. };
  8766. InternalPromise.resolve = function (value) {
  8767. var newPromise = new InternalPromise();
  8768. newPromise._resolve(value);
  8769. return newPromise;
  8770. };
  8771. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8772. promise.then(function (value) {
  8773. agregator.results[index] = value;
  8774. agregator.count++;
  8775. if (agregator.count === agregator.target) {
  8776. agregator.rootPromise._resolve(agregator.results);
  8777. }
  8778. return null;
  8779. }, function (reason) {
  8780. if (!agregator.rootPromise.isRejected) {
  8781. agregator.rootPromise._reject(reason);
  8782. }
  8783. });
  8784. };
  8785. InternalPromise.all = function (promises) {
  8786. var newPromise = new InternalPromise();
  8787. var agregator = new FulFillmentAgregator();
  8788. agregator.target = promises.length;
  8789. agregator.rootPromise = newPromise;
  8790. if (promises.length) {
  8791. for (var index = 0; index < promises.length; index++) {
  8792. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8793. }
  8794. }
  8795. else {
  8796. newPromise._resolve([]);
  8797. }
  8798. return newPromise;
  8799. };
  8800. return InternalPromise;
  8801. }());
  8802. /**
  8803. * Helper class that provides a small promise polyfill
  8804. */
  8805. var PromisePolyfill = /** @class */ (function () {
  8806. function PromisePolyfill() {
  8807. }
  8808. /**
  8809. * Static function used to check if the polyfill is required
  8810. * If this is the case then the function will inject the polyfill to window.Promise
  8811. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8812. */
  8813. PromisePolyfill.Apply = function (force) {
  8814. if (force === void 0) { force = false; }
  8815. if (force || typeof Promise === 'undefined') {
  8816. var root = window;
  8817. root.Promise = InternalPromise;
  8818. }
  8819. };
  8820. return PromisePolyfill;
  8821. }());
  8822. BABYLON.PromisePolyfill = PromisePolyfill;
  8823. })(BABYLON || (BABYLON = {}));
  8824. //# sourceMappingURL=babylon.promise.js.map
  8825. var BABYLON;
  8826. (function (BABYLON) {
  8827. var _AlphaState = /** @class */ (function () {
  8828. /**
  8829. * Initializes the state.
  8830. */
  8831. function _AlphaState() {
  8832. this._isAlphaBlendDirty = false;
  8833. this._isBlendFunctionParametersDirty = false;
  8834. this._isBlendEquationParametersDirty = false;
  8835. this._isBlendConstantsDirty = false;
  8836. this._alphaBlend = false;
  8837. this._blendFunctionParameters = new Array(4);
  8838. this._blendEquationParameters = new Array(2);
  8839. this._blendConstants = new Array(4);
  8840. this.reset();
  8841. }
  8842. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8843. get: function () {
  8844. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8845. },
  8846. enumerable: true,
  8847. configurable: true
  8848. });
  8849. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8850. get: function () {
  8851. return this._alphaBlend;
  8852. },
  8853. set: function (value) {
  8854. if (this._alphaBlend === value) {
  8855. return;
  8856. }
  8857. this._alphaBlend = value;
  8858. this._isAlphaBlendDirty = true;
  8859. },
  8860. enumerable: true,
  8861. configurable: true
  8862. });
  8863. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8864. if (this._blendConstants[0] === r &&
  8865. this._blendConstants[1] === g &&
  8866. this._blendConstants[2] === b &&
  8867. this._blendConstants[3] === a) {
  8868. return;
  8869. }
  8870. this._blendConstants[0] = r;
  8871. this._blendConstants[1] = g;
  8872. this._blendConstants[2] = b;
  8873. this._blendConstants[3] = a;
  8874. this._isBlendConstantsDirty = true;
  8875. };
  8876. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8877. if (this._blendFunctionParameters[0] === value0 &&
  8878. this._blendFunctionParameters[1] === value1 &&
  8879. this._blendFunctionParameters[2] === value2 &&
  8880. this._blendFunctionParameters[3] === value3) {
  8881. return;
  8882. }
  8883. this._blendFunctionParameters[0] = value0;
  8884. this._blendFunctionParameters[1] = value1;
  8885. this._blendFunctionParameters[2] = value2;
  8886. this._blendFunctionParameters[3] = value3;
  8887. this._isBlendFunctionParametersDirty = true;
  8888. };
  8889. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8890. if (this._blendEquationParameters[0] === rgb &&
  8891. this._blendEquationParameters[1] === alpha) {
  8892. return;
  8893. }
  8894. this._blendEquationParameters[0] = rgb;
  8895. this._blendEquationParameters[1] = alpha;
  8896. this._isBlendEquationParametersDirty = true;
  8897. };
  8898. _AlphaState.prototype.reset = function () {
  8899. this._alphaBlend = false;
  8900. this._blendFunctionParameters[0] = null;
  8901. this._blendFunctionParameters[1] = null;
  8902. this._blendFunctionParameters[2] = null;
  8903. this._blendFunctionParameters[3] = null;
  8904. this._blendEquationParameters[0] = null;
  8905. this._blendEquationParameters[1] = null;
  8906. this._blendConstants[0] = null;
  8907. this._blendConstants[1] = null;
  8908. this._blendConstants[2] = null;
  8909. this._blendConstants[3] = null;
  8910. this._isAlphaBlendDirty = true;
  8911. this._isBlendFunctionParametersDirty = false;
  8912. this._isBlendEquationParametersDirty = false;
  8913. this._isBlendConstantsDirty = false;
  8914. };
  8915. _AlphaState.prototype.apply = function (gl) {
  8916. if (!this.isDirty) {
  8917. return;
  8918. }
  8919. // Alpha blend
  8920. if (this._isAlphaBlendDirty) {
  8921. if (this._alphaBlend) {
  8922. gl.enable(gl.BLEND);
  8923. }
  8924. else {
  8925. gl.disable(gl.BLEND);
  8926. }
  8927. this._isAlphaBlendDirty = false;
  8928. }
  8929. // Alpha function
  8930. if (this._isBlendFunctionParametersDirty) {
  8931. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8932. this._isBlendFunctionParametersDirty = false;
  8933. }
  8934. // Alpha equation
  8935. if (this._isBlendEquationParametersDirty) {
  8936. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8937. this._isBlendEquationParametersDirty = false;
  8938. }
  8939. // Constants
  8940. if (this._isBlendConstantsDirty) {
  8941. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8942. this._isBlendConstantsDirty = false;
  8943. }
  8944. };
  8945. return _AlphaState;
  8946. }());
  8947. BABYLON._AlphaState = _AlphaState;
  8948. })(BABYLON || (BABYLON = {}));
  8949. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8950. var BABYLON;
  8951. (function (BABYLON) {
  8952. var _DepthCullingState = /** @class */ (function () {
  8953. /**
  8954. * Initializes the state.
  8955. */
  8956. function _DepthCullingState() {
  8957. this._isDepthTestDirty = false;
  8958. this._isDepthMaskDirty = false;
  8959. this._isDepthFuncDirty = false;
  8960. this._isCullFaceDirty = false;
  8961. this._isCullDirty = false;
  8962. this._isZOffsetDirty = false;
  8963. this._isFrontFaceDirty = false;
  8964. this.reset();
  8965. }
  8966. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8967. get: function () {
  8968. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8969. },
  8970. enumerable: true,
  8971. configurable: true
  8972. });
  8973. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8974. get: function () {
  8975. return this._zOffset;
  8976. },
  8977. set: function (value) {
  8978. if (this._zOffset === value) {
  8979. return;
  8980. }
  8981. this._zOffset = value;
  8982. this._isZOffsetDirty = true;
  8983. },
  8984. enumerable: true,
  8985. configurable: true
  8986. });
  8987. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8988. get: function () {
  8989. return this._cullFace;
  8990. },
  8991. set: function (value) {
  8992. if (this._cullFace === value) {
  8993. return;
  8994. }
  8995. this._cullFace = value;
  8996. this._isCullFaceDirty = true;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9002. get: function () {
  9003. return this._cull;
  9004. },
  9005. set: function (value) {
  9006. if (this._cull === value) {
  9007. return;
  9008. }
  9009. this._cull = value;
  9010. this._isCullDirty = true;
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9016. get: function () {
  9017. return this._depthFunc;
  9018. },
  9019. set: function (value) {
  9020. if (this._depthFunc === value) {
  9021. return;
  9022. }
  9023. this._depthFunc = value;
  9024. this._isDepthFuncDirty = true;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9030. get: function () {
  9031. return this._depthMask;
  9032. },
  9033. set: function (value) {
  9034. if (this._depthMask === value) {
  9035. return;
  9036. }
  9037. this._depthMask = value;
  9038. this._isDepthMaskDirty = true;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9044. get: function () {
  9045. return this._depthTest;
  9046. },
  9047. set: function (value) {
  9048. if (this._depthTest === value) {
  9049. return;
  9050. }
  9051. this._depthTest = value;
  9052. this._isDepthTestDirty = true;
  9053. },
  9054. enumerable: true,
  9055. configurable: true
  9056. });
  9057. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9058. get: function () {
  9059. return this._frontFace;
  9060. },
  9061. set: function (value) {
  9062. if (this._frontFace === value) {
  9063. return;
  9064. }
  9065. this._frontFace = value;
  9066. this._isFrontFaceDirty = true;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. _DepthCullingState.prototype.reset = function () {
  9072. this._depthMask = true;
  9073. this._depthTest = true;
  9074. this._depthFunc = null;
  9075. this._cullFace = null;
  9076. this._cull = null;
  9077. this._zOffset = 0;
  9078. this._frontFace = null;
  9079. this._isDepthTestDirty = true;
  9080. this._isDepthMaskDirty = true;
  9081. this._isDepthFuncDirty = false;
  9082. this._isCullFaceDirty = false;
  9083. this._isCullDirty = false;
  9084. this._isZOffsetDirty = false;
  9085. this._isFrontFaceDirty = false;
  9086. };
  9087. _DepthCullingState.prototype.apply = function (gl) {
  9088. if (!this.isDirty) {
  9089. return;
  9090. }
  9091. // Cull
  9092. if (this._isCullDirty) {
  9093. if (this.cull) {
  9094. gl.enable(gl.CULL_FACE);
  9095. }
  9096. else {
  9097. gl.disable(gl.CULL_FACE);
  9098. }
  9099. this._isCullDirty = false;
  9100. }
  9101. // Cull face
  9102. if (this._isCullFaceDirty) {
  9103. gl.cullFace(this.cullFace);
  9104. this._isCullFaceDirty = false;
  9105. }
  9106. // Depth mask
  9107. if (this._isDepthMaskDirty) {
  9108. gl.depthMask(this.depthMask);
  9109. this._isDepthMaskDirty = false;
  9110. }
  9111. // Depth test
  9112. if (this._isDepthTestDirty) {
  9113. if (this.depthTest) {
  9114. gl.enable(gl.DEPTH_TEST);
  9115. }
  9116. else {
  9117. gl.disable(gl.DEPTH_TEST);
  9118. }
  9119. this._isDepthTestDirty = false;
  9120. }
  9121. // Depth func
  9122. if (this._isDepthFuncDirty) {
  9123. gl.depthFunc(this.depthFunc);
  9124. this._isDepthFuncDirty = false;
  9125. }
  9126. // zOffset
  9127. if (this._isZOffsetDirty) {
  9128. if (this.zOffset) {
  9129. gl.enable(gl.POLYGON_OFFSET_FILL);
  9130. gl.polygonOffset(this.zOffset, 0);
  9131. }
  9132. else {
  9133. gl.disable(gl.POLYGON_OFFSET_FILL);
  9134. }
  9135. this._isZOffsetDirty = false;
  9136. }
  9137. // Front face
  9138. if (this._isFrontFaceDirty) {
  9139. gl.frontFace(this.frontFace);
  9140. this._isFrontFaceDirty = false;
  9141. }
  9142. };
  9143. return _DepthCullingState;
  9144. }());
  9145. BABYLON._DepthCullingState = _DepthCullingState;
  9146. })(BABYLON || (BABYLON = {}));
  9147. //# sourceMappingURL=babylon.depthCullingState.js.map
  9148. var BABYLON;
  9149. (function (BABYLON) {
  9150. var _StencilState = /** @class */ (function () {
  9151. function _StencilState() {
  9152. this._isStencilTestDirty = false;
  9153. this._isStencilMaskDirty = false;
  9154. this._isStencilFuncDirty = false;
  9155. this._isStencilOpDirty = false;
  9156. this.reset();
  9157. }
  9158. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9159. get: function () {
  9160. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9161. },
  9162. enumerable: true,
  9163. configurable: true
  9164. });
  9165. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9166. get: function () {
  9167. return this._stencilFunc;
  9168. },
  9169. set: function (value) {
  9170. if (this._stencilFunc === value) {
  9171. return;
  9172. }
  9173. this._stencilFunc = value;
  9174. this._isStencilFuncDirty = true;
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9180. get: function () {
  9181. return this._stencilFuncRef;
  9182. },
  9183. set: function (value) {
  9184. if (this._stencilFuncRef === value) {
  9185. return;
  9186. }
  9187. this._stencilFuncRef = value;
  9188. this._isStencilFuncDirty = true;
  9189. },
  9190. enumerable: true,
  9191. configurable: true
  9192. });
  9193. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9194. get: function () {
  9195. return this._stencilFuncMask;
  9196. },
  9197. set: function (value) {
  9198. if (this._stencilFuncMask === value) {
  9199. return;
  9200. }
  9201. this._stencilFuncMask = value;
  9202. this._isStencilFuncDirty = true;
  9203. },
  9204. enumerable: true,
  9205. configurable: true
  9206. });
  9207. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9208. get: function () {
  9209. return this._stencilOpStencilFail;
  9210. },
  9211. set: function (value) {
  9212. if (this._stencilOpStencilFail === value) {
  9213. return;
  9214. }
  9215. this._stencilOpStencilFail = value;
  9216. this._isStencilOpDirty = true;
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9222. get: function () {
  9223. return this._stencilOpDepthFail;
  9224. },
  9225. set: function (value) {
  9226. if (this._stencilOpDepthFail === value) {
  9227. return;
  9228. }
  9229. this._stencilOpDepthFail = value;
  9230. this._isStencilOpDirty = true;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9236. get: function () {
  9237. return this._stencilOpStencilDepthPass;
  9238. },
  9239. set: function (value) {
  9240. if (this._stencilOpStencilDepthPass === value) {
  9241. return;
  9242. }
  9243. this._stencilOpStencilDepthPass = value;
  9244. this._isStencilOpDirty = true;
  9245. },
  9246. enumerable: true,
  9247. configurable: true
  9248. });
  9249. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9250. get: function () {
  9251. return this._stencilMask;
  9252. },
  9253. set: function (value) {
  9254. if (this._stencilMask === value) {
  9255. return;
  9256. }
  9257. this._stencilMask = value;
  9258. this._isStencilMaskDirty = true;
  9259. },
  9260. enumerable: true,
  9261. configurable: true
  9262. });
  9263. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9264. get: function () {
  9265. return this._stencilTest;
  9266. },
  9267. set: function (value) {
  9268. if (this._stencilTest === value) {
  9269. return;
  9270. }
  9271. this._stencilTest = value;
  9272. this._isStencilTestDirty = true;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. _StencilState.prototype.reset = function () {
  9278. this._stencilTest = false;
  9279. this._stencilMask = 0xFF;
  9280. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9281. this._stencilFuncRef = 1;
  9282. this._stencilFuncMask = 0xFF;
  9283. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9284. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9285. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9286. this._isStencilTestDirty = true;
  9287. this._isStencilMaskDirty = true;
  9288. this._isStencilFuncDirty = true;
  9289. this._isStencilOpDirty = true;
  9290. };
  9291. _StencilState.prototype.apply = function (gl) {
  9292. if (!this.isDirty) {
  9293. return;
  9294. }
  9295. // Stencil test
  9296. if (this._isStencilTestDirty) {
  9297. if (this.stencilTest) {
  9298. gl.enable(gl.STENCIL_TEST);
  9299. }
  9300. else {
  9301. gl.disable(gl.STENCIL_TEST);
  9302. }
  9303. this._isStencilTestDirty = false;
  9304. }
  9305. // Stencil mask
  9306. if (this._isStencilMaskDirty) {
  9307. gl.stencilMask(this.stencilMask);
  9308. this._isStencilMaskDirty = false;
  9309. }
  9310. // Stencil func
  9311. if (this._isStencilFuncDirty) {
  9312. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9313. this._isStencilFuncDirty = false;
  9314. }
  9315. // Stencil op
  9316. if (this._isStencilOpDirty) {
  9317. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9318. this._isStencilOpDirty = false;
  9319. }
  9320. };
  9321. return _StencilState;
  9322. }());
  9323. BABYLON._StencilState = _StencilState;
  9324. })(BABYLON || (BABYLON = {}));
  9325. //# sourceMappingURL=babylon.stencilState.js.map
  9326. var BABYLON;
  9327. (function (BABYLON) {
  9328. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9329. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9330. };
  9331. var compileRawShader = function (gl, source, type) {
  9332. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9333. gl.shaderSource(shader, source);
  9334. gl.compileShader(shader);
  9335. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9336. var log = gl.getShaderInfoLog(shader);
  9337. if (log) {
  9338. throw new Error(log);
  9339. }
  9340. }
  9341. if (!shader) {
  9342. throw new Error("Something went wrong while compile the shader.");
  9343. }
  9344. return shader;
  9345. };
  9346. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9347. var magFilter = gl.NEAREST;
  9348. var minFilter = gl.NEAREST;
  9349. switch (samplingMode) {
  9350. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9351. magFilter = gl.LINEAR;
  9352. if (generateMipMaps) {
  9353. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9354. }
  9355. else {
  9356. minFilter = gl.LINEAR;
  9357. }
  9358. break;
  9359. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9360. magFilter = gl.LINEAR;
  9361. if (generateMipMaps) {
  9362. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9363. }
  9364. else {
  9365. minFilter = gl.LINEAR;
  9366. }
  9367. break;
  9368. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9369. magFilter = gl.NEAREST;
  9370. if (generateMipMaps) {
  9371. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9372. }
  9373. else {
  9374. minFilter = gl.NEAREST;
  9375. }
  9376. break;
  9377. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9378. magFilter = gl.NEAREST;
  9379. if (generateMipMaps) {
  9380. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9381. }
  9382. else {
  9383. minFilter = gl.NEAREST;
  9384. }
  9385. break;
  9386. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9387. magFilter = gl.NEAREST;
  9388. if (generateMipMaps) {
  9389. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9390. }
  9391. else {
  9392. minFilter = gl.LINEAR;
  9393. }
  9394. break;
  9395. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9396. magFilter = gl.NEAREST;
  9397. if (generateMipMaps) {
  9398. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9399. }
  9400. else {
  9401. minFilter = gl.LINEAR;
  9402. }
  9403. break;
  9404. case BABYLON.Texture.NEAREST_LINEAR:
  9405. magFilter = gl.NEAREST;
  9406. minFilter = gl.LINEAR;
  9407. break;
  9408. case BABYLON.Texture.NEAREST_NEAREST:
  9409. magFilter = gl.NEAREST;
  9410. minFilter = gl.NEAREST;
  9411. break;
  9412. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9413. magFilter = gl.LINEAR;
  9414. if (generateMipMaps) {
  9415. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9416. }
  9417. else {
  9418. minFilter = gl.NEAREST;
  9419. }
  9420. break;
  9421. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9422. magFilter = gl.LINEAR;
  9423. if (generateMipMaps) {
  9424. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9425. }
  9426. else {
  9427. minFilter = gl.NEAREST;
  9428. }
  9429. break;
  9430. case BABYLON.Texture.LINEAR_LINEAR:
  9431. magFilter = gl.LINEAR;
  9432. minFilter = gl.LINEAR;
  9433. break;
  9434. case BABYLON.Texture.LINEAR_NEAREST:
  9435. magFilter = gl.LINEAR;
  9436. minFilter = gl.NEAREST;
  9437. break;
  9438. }
  9439. return {
  9440. min: minFilter,
  9441. mag: magFilter
  9442. };
  9443. };
  9444. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9445. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9446. var img;
  9447. var onload = function () {
  9448. loadedImages[index] = img;
  9449. loadedImages._internalCount++;
  9450. if (scene) {
  9451. scene._removePendingData(img);
  9452. }
  9453. if (loadedImages._internalCount === 6) {
  9454. onfinish(loadedImages);
  9455. }
  9456. };
  9457. var onerror = function (message, exception) {
  9458. if (scene) {
  9459. scene._removePendingData(img);
  9460. }
  9461. if (onErrorCallBack) {
  9462. onErrorCallBack(message, exception);
  9463. }
  9464. };
  9465. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9466. if (scene) {
  9467. scene._addPendingData(img);
  9468. }
  9469. };
  9470. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9471. if (onError === void 0) { onError = null; }
  9472. var loadedImages = [];
  9473. loadedImages._internalCount = 0;
  9474. for (var index = 0; index < 6; index++) {
  9475. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9476. }
  9477. };
  9478. var BufferPointer = /** @class */ (function () {
  9479. function BufferPointer() {
  9480. }
  9481. return BufferPointer;
  9482. }());
  9483. var InstancingAttributeInfo = /** @class */ (function () {
  9484. function InstancingAttributeInfo() {
  9485. }
  9486. return InstancingAttributeInfo;
  9487. }());
  9488. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9489. /**
  9490. * Define options used to create a render target texture
  9491. */
  9492. var RenderTargetCreationOptions = /** @class */ (function () {
  9493. function RenderTargetCreationOptions() {
  9494. }
  9495. return RenderTargetCreationOptions;
  9496. }());
  9497. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9498. /**
  9499. * Regroup several parameters relative to the browser in use
  9500. */
  9501. var EngineCapabilities = /** @class */ (function () {
  9502. function EngineCapabilities() {
  9503. }
  9504. return EngineCapabilities;
  9505. }());
  9506. BABYLON.EngineCapabilities = EngineCapabilities;
  9507. /**
  9508. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9509. */
  9510. var Engine = /** @class */ (function () {
  9511. /**
  9512. * @constructor
  9513. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9514. * @param antialias defines enable antialiasing (default: false)
  9515. * @param options defines further options to be sent to the getContext() function
  9516. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9517. */
  9518. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9519. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9520. var _this = this;
  9521. // Public members
  9522. this.forcePOTTextures = false;
  9523. this.isFullscreen = false;
  9524. this.isPointerLock = false;
  9525. this.cullBackFaces = true;
  9526. this.renderEvenInBackground = true;
  9527. this.preventCacheWipeBetweenFrames = false;
  9528. // To enable/disable IDB support and avoid XHR on .manifest
  9529. this.enableOfflineSupport = false;
  9530. this.scenes = new Array();
  9531. this.postProcesses = new Array();
  9532. // Observables
  9533. /**
  9534. * Observable event triggered each time the rendering canvas is resized
  9535. */
  9536. this.onResizeObservable = new BABYLON.Observable();
  9537. /**
  9538. * Observable event triggered each time the canvas loses focus
  9539. */
  9540. this.onCanvasBlurObservable = new BABYLON.Observable();
  9541. /**
  9542. * Observable event triggered each time the canvas gains focus
  9543. */
  9544. this.onCanvasFocusObservable = new BABYLON.Observable();
  9545. /**
  9546. * Observable event triggered each time the canvas receives pointerout event
  9547. */
  9548. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9549. /**
  9550. * Observable event triggered before each texture is initialized
  9551. */
  9552. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9553. //WebVR
  9554. this._vrDisplay = undefined;
  9555. this._vrSupported = false;
  9556. this._vrExclusivePointerMode = false;
  9557. // Uniform buffers list
  9558. this.disableUniformBuffers = false;
  9559. this._uniformBuffers = new Array();
  9560. // Observables
  9561. /**
  9562. * Observable raised when the engine begins a new frame
  9563. */
  9564. this.onBeginFrameObservable = new BABYLON.Observable();
  9565. /**
  9566. * Observable raised when the engine ends the current frame
  9567. */
  9568. this.onEndFrameObservable = new BABYLON.Observable();
  9569. /**
  9570. * Observable raised when the engine is about to compile a shader
  9571. */
  9572. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9573. /**
  9574. * Observable raised when the engine has jsut compiled a shader
  9575. */
  9576. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9577. this._windowIsBackground = false;
  9578. this._webGLVersion = 1.0;
  9579. this._badOS = false;
  9580. this._badDesktopOS = false;
  9581. /**
  9582. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9583. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9584. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9585. */
  9586. this.disableTextureBindingOptimization = false;
  9587. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9588. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9589. this.onVRRequestPresentStart = new BABYLON.Observable();
  9590. this._colorWrite = true;
  9591. this._drawCalls = new BABYLON.PerfCounter();
  9592. this._textureCollisions = new BABYLON.PerfCounter();
  9593. this._renderingQueueLaunched = false;
  9594. this._activeRenderLoops = new Array();
  9595. // Deterministic lockstepMaxSteps
  9596. this._deterministicLockstep = false;
  9597. this._lockstepMaxSteps = 4;
  9598. // Lost context
  9599. this.onContextLostObservable = new BABYLON.Observable();
  9600. this.onContextRestoredObservable = new BABYLON.Observable();
  9601. this._contextWasLost = false;
  9602. this._doNotHandleContextLost = false;
  9603. // FPS
  9604. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9605. this._fps = 60;
  9606. this._deltaTime = 0;
  9607. /**
  9608. * Turn this value on if you want to pause FPS computation when in background
  9609. */
  9610. this.disablePerformanceMonitorInBackground = false;
  9611. // States
  9612. this._depthCullingState = new BABYLON._DepthCullingState();
  9613. this._stencilState = new BABYLON._StencilState();
  9614. this._alphaState = new BABYLON._AlphaState();
  9615. this._alphaMode = Engine.ALPHA_DISABLE;
  9616. // Cache
  9617. this._internalTexturesCache = new Array();
  9618. this._activeChannel = 0;
  9619. this._currentTextureChannel = -1;
  9620. this._boundTexturesCache = {};
  9621. this._compiledEffects = {};
  9622. this._vertexAttribArraysEnabled = [];
  9623. this._uintIndicesCurrentlySet = false;
  9624. this._currentBoundBuffer = new Array();
  9625. this._currentBufferPointers = new Array();
  9626. this._currentInstanceLocations = new Array();
  9627. this._currentInstanceBuffers = new Array();
  9628. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9629. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9630. this._vaoRecordInProgress = false;
  9631. this._mustWipeVertexAttributes = false;
  9632. this._nextFreeTextureSlots = new Array();
  9633. this._maxSimultaneousTextures = 0;
  9634. this._activeRequests = new Array();
  9635. // Hardware supported Compressed Textures
  9636. this._texturesSupported = new Array();
  9637. this._onVRFullScreenTriggered = function () {
  9638. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9639. //get the old size before we change
  9640. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9641. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9642. //get the width and height, change the render size
  9643. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9644. _this.setHardwareScalingLevel(1);
  9645. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9646. }
  9647. else {
  9648. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9649. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9650. }
  9651. };
  9652. this._boundUniforms = {};
  9653. // Register promises
  9654. BABYLON.PromisePolyfill.Apply();
  9655. var canvas = null;
  9656. Engine.Instances.push(this);
  9657. if (!canvasOrContext) {
  9658. return;
  9659. }
  9660. options = options || {};
  9661. if (canvasOrContext.getContext) {
  9662. canvas = canvasOrContext;
  9663. this._renderingCanvas = canvas;
  9664. if (antialias != null) {
  9665. options.antialias = antialias;
  9666. }
  9667. if (options.deterministicLockstep === undefined) {
  9668. options.deterministicLockstep = false;
  9669. }
  9670. if (options.lockstepMaxSteps === undefined) {
  9671. options.lockstepMaxSteps = 4;
  9672. }
  9673. if (options.preserveDrawingBuffer === undefined) {
  9674. options.preserveDrawingBuffer = false;
  9675. }
  9676. if (options.audioEngine === undefined) {
  9677. options.audioEngine = true;
  9678. }
  9679. if (options.stencil === undefined) {
  9680. options.stencil = true;
  9681. }
  9682. this._deterministicLockstep = options.deterministicLockstep;
  9683. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9684. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9685. // Exceptions
  9686. if (navigator && navigator.userAgent) {
  9687. var ua = navigator.userAgent;
  9688. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9689. var exception = _a[_i];
  9690. var key = exception.key;
  9691. var targets = exception.targets;
  9692. if (ua.indexOf(key) > -1) {
  9693. if (exception.capture && exception.captureConstraint) {
  9694. var capture = exception.capture;
  9695. var constraint = exception.captureConstraint;
  9696. var regex = new RegExp(capture);
  9697. var matches = regex.exec(ua);
  9698. if (matches && matches.length > 0) {
  9699. var capturedValue = parseInt(matches[matches.length - 1]);
  9700. if (capturedValue >= constraint) {
  9701. continue;
  9702. }
  9703. }
  9704. }
  9705. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9706. var target = targets_1[_b];
  9707. switch (target) {
  9708. case "uniformBuffer":
  9709. this.disableUniformBuffers = true;
  9710. break;
  9711. case "textureBindingOptimization":
  9712. this.disableTextureBindingOptimization = true;
  9713. break;
  9714. }
  9715. }
  9716. break;
  9717. }
  9718. }
  9719. }
  9720. // GL
  9721. if (!options.disableWebGL2Support) {
  9722. try {
  9723. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9724. if (this._gl) {
  9725. this._webGLVersion = 2.0;
  9726. }
  9727. }
  9728. catch (e) {
  9729. // Do nothing
  9730. }
  9731. }
  9732. if (!this._gl) {
  9733. if (!canvas) {
  9734. throw new Error("The provided canvas is null or undefined.");
  9735. }
  9736. try {
  9737. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9738. }
  9739. catch (e) {
  9740. throw new Error("WebGL not supported");
  9741. }
  9742. }
  9743. if (!this._gl) {
  9744. throw new Error("WebGL not supported");
  9745. }
  9746. this._onCanvasFocus = function () {
  9747. _this.onCanvasFocusObservable.notifyObservers(_this);
  9748. };
  9749. this._onCanvasBlur = function () {
  9750. _this.onCanvasBlurObservable.notifyObservers(_this);
  9751. };
  9752. canvas.addEventListener("focus", this._onCanvasFocus);
  9753. canvas.addEventListener("blur", this._onCanvasBlur);
  9754. this._onBlur = function () {
  9755. if (_this.disablePerformanceMonitorInBackground) {
  9756. _this._performanceMonitor.disable();
  9757. }
  9758. _this._windowIsBackground = true;
  9759. };
  9760. this._onFocus = function () {
  9761. if (_this.disablePerformanceMonitorInBackground) {
  9762. _this._performanceMonitor.enable();
  9763. }
  9764. _this._windowIsBackground = false;
  9765. };
  9766. this._onCanvasPointerOut = function () {
  9767. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9768. };
  9769. window.addEventListener("blur", this._onBlur);
  9770. window.addEventListener("focus", this._onFocus);
  9771. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9772. // Context lost
  9773. if (!this._doNotHandleContextLost) {
  9774. this._onContextLost = function (evt) {
  9775. evt.preventDefault();
  9776. _this._contextWasLost = true;
  9777. BABYLON.Tools.Warn("WebGL context lost.");
  9778. _this.onContextLostObservable.notifyObservers(_this);
  9779. };
  9780. this._onContextRestored = function (evt) {
  9781. // Adding a timeout to avoid race condition at browser level
  9782. setTimeout(function () {
  9783. // Rebuild gl context
  9784. _this._initGLContext();
  9785. // Rebuild effects
  9786. _this._rebuildEffects();
  9787. // Rebuild textures
  9788. _this._rebuildInternalTextures();
  9789. // Rebuild buffers
  9790. _this._rebuildBuffers();
  9791. // Cache
  9792. _this.wipeCaches(true);
  9793. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9794. _this.onContextRestoredObservable.notifyObservers(_this);
  9795. _this._contextWasLost = false;
  9796. }, 0);
  9797. };
  9798. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9799. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9800. }
  9801. }
  9802. else {
  9803. this._gl = canvasOrContext;
  9804. this._renderingCanvas = this._gl.canvas;
  9805. if (this._gl.renderbufferStorageMultisample) {
  9806. this._webGLVersion = 2.0;
  9807. }
  9808. options.stencil = this._gl.getContextAttributes().stencil;
  9809. }
  9810. // Viewport
  9811. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9812. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9813. this.resize();
  9814. this._isStencilEnable = options.stencil ? true : false;
  9815. this._initGLContext();
  9816. if (canvas) {
  9817. // Fullscreen
  9818. this._onFullscreenChange = function () {
  9819. if (document.fullscreen !== undefined) {
  9820. _this.isFullscreen = document.fullscreen;
  9821. }
  9822. else if (document.mozFullScreen !== undefined) {
  9823. _this.isFullscreen = document.mozFullScreen;
  9824. }
  9825. else if (document.webkitIsFullScreen !== undefined) {
  9826. _this.isFullscreen = document.webkitIsFullScreen;
  9827. }
  9828. else if (document.msIsFullScreen !== undefined) {
  9829. _this.isFullscreen = document.msIsFullScreen;
  9830. }
  9831. // Pointer lock
  9832. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9833. canvas.requestPointerLock = canvas.requestPointerLock ||
  9834. canvas.msRequestPointerLock ||
  9835. canvas.mozRequestPointerLock ||
  9836. canvas.webkitRequestPointerLock;
  9837. if (canvas.requestPointerLock) {
  9838. canvas.requestPointerLock();
  9839. }
  9840. }
  9841. };
  9842. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9843. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9844. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9845. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9846. // Pointer lock
  9847. this._onPointerLockChange = function () {
  9848. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9849. document.webkitPointerLockElement === canvas ||
  9850. document.msPointerLockElement === canvas ||
  9851. document.pointerLockElement === canvas);
  9852. };
  9853. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9854. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9855. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9856. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9857. this._onVRDisplayPointerRestricted = function () {
  9858. if (canvas) {
  9859. canvas.requestPointerLock();
  9860. }
  9861. };
  9862. this._onVRDisplayPointerUnrestricted = function () {
  9863. document.exitPointerLock();
  9864. };
  9865. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9866. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9867. }
  9868. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9869. Engine.audioEngine = new BABYLON.AudioEngine();
  9870. }
  9871. // Prepare buffer pointers
  9872. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9873. this._currentBufferPointers[i] = new BufferPointer();
  9874. }
  9875. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9876. // Load WebVR Devices
  9877. if (options.autoEnableWebVR) {
  9878. this.initWebVR();
  9879. }
  9880. // Detect if we are running on a faulty buggy OS.
  9881. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9882. // Detect if we are running on a faulty buggy desktop OS.
  9883. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9884. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9885. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9886. }
  9887. Object.defineProperty(Engine, "LastCreatedEngine", {
  9888. get: function () {
  9889. if (Engine.Instances.length === 0) {
  9890. return null;
  9891. }
  9892. return Engine.Instances[Engine.Instances.length - 1];
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(Engine, "LastCreatedScene", {
  9898. get: function () {
  9899. var lastCreatedEngine = Engine.LastCreatedEngine;
  9900. if (!lastCreatedEngine) {
  9901. return null;
  9902. }
  9903. if (lastCreatedEngine.scenes.length === 0) {
  9904. return null;
  9905. }
  9906. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. /**
  9912. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9913. */
  9914. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9915. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9916. var engine = Engine.Instances[engineIndex];
  9917. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9918. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9919. }
  9920. }
  9921. };
  9922. Object.defineProperty(Engine, "NEVER", {
  9923. get: function () {
  9924. return Engine._NEVER;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Engine, "ALWAYS", {
  9930. get: function () {
  9931. return Engine._ALWAYS;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(Engine, "LESS", {
  9937. get: function () {
  9938. return Engine._LESS;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Engine, "EQUAL", {
  9944. get: function () {
  9945. return Engine._EQUAL;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Engine, "LEQUAL", {
  9951. get: function () {
  9952. return Engine._LEQUAL;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Engine, "GREATER", {
  9958. get: function () {
  9959. return Engine._GREATER;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(Engine, "GEQUAL", {
  9965. get: function () {
  9966. return Engine._GEQUAL;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(Engine, "NOTEQUAL", {
  9972. get: function () {
  9973. return Engine._NOTEQUAL;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(Engine, "KEEP", {
  9979. get: function () {
  9980. return Engine._KEEP;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(Engine, "REPLACE", {
  9986. get: function () {
  9987. return Engine._REPLACE;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(Engine, "INCR", {
  9993. get: function () {
  9994. return Engine._INCR;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Engine, "DECR", {
  10000. get: function () {
  10001. return Engine._DECR;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Engine, "INVERT", {
  10007. get: function () {
  10008. return Engine._INVERT;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(Engine, "INCR_WRAP", {
  10014. get: function () {
  10015. return Engine._INCR_WRAP;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(Engine, "DECR_WRAP", {
  10021. get: function () {
  10022. return Engine._DECR_WRAP;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10028. get: function () {
  10029. return Engine._ALPHA_DISABLE;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10035. get: function () {
  10036. return Engine._ALPHA_ONEONE;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(Engine, "ALPHA_ADD", {
  10042. get: function () {
  10043. return Engine._ALPHA_ADD;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10049. get: function () {
  10050. return Engine._ALPHA_COMBINE;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10056. get: function () {
  10057. return Engine._ALPHA_SUBTRACT;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10063. get: function () {
  10064. return Engine._ALPHA_MULTIPLY;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10070. get: function () {
  10071. return Engine._ALPHA_MAXIMIZED;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10077. get: function () {
  10078. return Engine._ALPHA_PREMULTIPLIED;
  10079. },
  10080. enumerable: true,
  10081. configurable: true
  10082. });
  10083. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10084. get: function () {
  10085. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10091. get: function () {
  10092. return Engine._ALPHA_INTERPOLATE;
  10093. },
  10094. enumerable: true,
  10095. configurable: true
  10096. });
  10097. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10098. get: function () {
  10099. return Engine._ALPHA_SCREENMODE;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10105. get: function () {
  10106. return Engine._DELAYLOADSTATE_NONE;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10112. get: function () {
  10113. return Engine._DELAYLOADSTATE_LOADED;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10119. get: function () {
  10120. return Engine._DELAYLOADSTATE_LOADING;
  10121. },
  10122. enumerable: true,
  10123. configurable: true
  10124. });
  10125. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10126. get: function () {
  10127. return Engine._DELAYLOADSTATE_NOTLOADED;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10133. get: function () {
  10134. return Engine._TEXTUREFORMAT_ALPHA;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10140. get: function () {
  10141. return Engine._TEXTUREFORMAT_LUMINANCE;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10147. get: function () {
  10148. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10154. get: function () {
  10155. return Engine._TEXTUREFORMAT_RGB;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10161. get: function () {
  10162. return Engine._TEXTUREFORMAT_RGBA;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10168. get: function () {
  10169. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10175. get: function () {
  10176. return Engine._TEXTURETYPE_FLOAT;
  10177. },
  10178. enumerable: true,
  10179. configurable: true
  10180. });
  10181. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10182. get: function () {
  10183. return Engine._TEXTURETYPE_HALF_FLOAT;
  10184. },
  10185. enumerable: true,
  10186. configurable: true
  10187. });
  10188. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10189. get: function () {
  10190. return Engine._SCALEMODE_FLOOR;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10196. get: function () {
  10197. return Engine._SCALEMODE_NEAREST;
  10198. },
  10199. enumerable: true,
  10200. configurable: true
  10201. });
  10202. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10203. get: function () {
  10204. return Engine._SCALEMODE_CEILING;
  10205. },
  10206. enumerable: true,
  10207. configurable: true
  10208. });
  10209. Object.defineProperty(Engine, "Version", {
  10210. get: function () {
  10211. return "3.2.0-alpha6";
  10212. },
  10213. enumerable: true,
  10214. configurable: true
  10215. });
  10216. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10217. get: function () {
  10218. return this._vrExclusivePointerMode;
  10219. },
  10220. enumerable: true,
  10221. configurable: true
  10222. });
  10223. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10224. get: function () {
  10225. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10231. get: function () {
  10232. return this._webGLVersion < 2 || this.forcePOTTextures;
  10233. },
  10234. enumerable: true,
  10235. configurable: true
  10236. });
  10237. Object.defineProperty(Engine.prototype, "badOS", {
  10238. get: function () {
  10239. return this._badOS;
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10245. get: function () {
  10246. return this._badDesktopOS;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10252. get: function () {
  10253. return this._performanceMonitor;
  10254. },
  10255. enumerable: true,
  10256. configurable: true
  10257. });
  10258. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10259. get: function () {
  10260. return this._texturesSupported;
  10261. },
  10262. enumerable: true,
  10263. configurable: true
  10264. });
  10265. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10266. get: function () {
  10267. return this._textureFormatInUse;
  10268. },
  10269. enumerable: true,
  10270. configurable: true
  10271. });
  10272. Object.defineProperty(Engine.prototype, "currentViewport", {
  10273. get: function () {
  10274. return this._cachedViewport;
  10275. },
  10276. enumerable: true,
  10277. configurable: true
  10278. });
  10279. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10280. // Empty texture
  10281. get: function () {
  10282. if (!this._emptyTexture) {
  10283. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10284. }
  10285. return this._emptyTexture;
  10286. },
  10287. enumerable: true,
  10288. configurable: true
  10289. });
  10290. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10291. get: function () {
  10292. if (!this._emptyTexture3D) {
  10293. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10294. }
  10295. return this._emptyTexture3D;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10301. get: function () {
  10302. if (!this._emptyCubeTexture) {
  10303. var faceData = new Uint8Array(4);
  10304. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10305. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10306. }
  10307. return this._emptyCubeTexture;
  10308. },
  10309. enumerable: true,
  10310. configurable: true
  10311. });
  10312. Engine.prototype._rebuildInternalTextures = function () {
  10313. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10314. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10315. var internalTexture = currentState_1[_i];
  10316. internalTexture._rebuild();
  10317. }
  10318. };
  10319. Engine.prototype._rebuildEffects = function () {
  10320. for (var key in this._compiledEffects) {
  10321. var effect = this._compiledEffects[key];
  10322. effect._prepareEffect();
  10323. }
  10324. BABYLON.Effect.ResetCache();
  10325. };
  10326. Engine.prototype._rebuildBuffers = function () {
  10327. // Index / Vertex
  10328. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10329. var scene = _a[_i];
  10330. scene.resetCachedMaterial();
  10331. scene._rebuildGeometries();
  10332. scene._rebuildTextures();
  10333. }
  10334. // Uniforms
  10335. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10336. var uniformBuffer = _c[_b];
  10337. uniformBuffer._rebuild();
  10338. }
  10339. };
  10340. Engine.prototype._initGLContext = function () {
  10341. // Caps
  10342. this._caps = new EngineCapabilities();
  10343. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10344. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10345. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10346. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10347. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10348. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10349. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10350. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10351. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10352. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10353. // Infos
  10354. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10355. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10356. if (rendererInfo != null) {
  10357. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10358. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10359. }
  10360. if (!this._glVendor) {
  10361. this._glVendor = "Unknown vendor";
  10362. }
  10363. if (!this._glRenderer) {
  10364. this._glRenderer = "Unknown renderer";
  10365. }
  10366. // Constants
  10367. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10368. if (this._gl.RGBA16F !== 0x881A) {
  10369. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10370. }
  10371. if (this._gl.RGBA32F !== 0x8814) {
  10372. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10373. }
  10374. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10375. this._gl.DEPTH24_STENCIL8 = 35056;
  10376. }
  10377. // Extensions
  10378. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10379. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10380. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10381. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10382. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10383. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10384. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10385. 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');
  10386. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10387. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10388. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10389. this._caps.highPrecisionShaderSupported = true;
  10390. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10391. if (this._caps.timerQuery) {
  10392. if (this._webGLVersion === 1) {
  10393. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10394. }
  10395. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10396. }
  10397. // Checks if some of the format renders first to allow the use of webgl inspector.
  10398. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10399. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10400. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10401. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10402. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10403. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10404. if (this._webGLVersion > 1) {
  10405. this._gl.HALF_FLOAT_OES = 0x140B;
  10406. }
  10407. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10408. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10409. // Draw buffers
  10410. if (this._webGLVersion > 1) {
  10411. this._caps.drawBuffersExtension = true;
  10412. }
  10413. else {
  10414. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10415. if (drawBuffersExtension !== null) {
  10416. this._caps.drawBuffersExtension = true;
  10417. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10418. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10419. for (var i = 0; i < 16; i++) {
  10420. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10421. }
  10422. }
  10423. else {
  10424. this._caps.drawBuffersExtension = false;
  10425. }
  10426. }
  10427. // Depth Texture
  10428. if (this._webGLVersion > 1) {
  10429. this._caps.depthTextureExtension = true;
  10430. }
  10431. else {
  10432. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10433. if (depthTextureExtension != null) {
  10434. this._caps.depthTextureExtension = true;
  10435. }
  10436. }
  10437. // Vertex array object
  10438. if (this._webGLVersion > 1) {
  10439. this._caps.vertexArrayObject = true;
  10440. }
  10441. else {
  10442. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10443. if (vertexArrayObjectExtension != null) {
  10444. this._caps.vertexArrayObject = true;
  10445. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10446. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10447. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10448. }
  10449. else {
  10450. this._caps.vertexArrayObject = false;
  10451. }
  10452. }
  10453. // Instances count
  10454. if (this._webGLVersion > 1) {
  10455. this._caps.instancedArrays = true;
  10456. }
  10457. else {
  10458. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10459. if (instanceExtension != null) {
  10460. this._caps.instancedArrays = true;
  10461. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10462. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10463. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10464. }
  10465. else {
  10466. this._caps.instancedArrays = false;
  10467. }
  10468. }
  10469. // Intelligently add supported compressed formats in order to check for.
  10470. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10471. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10472. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10473. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10474. if (this._caps.astc)
  10475. this.texturesSupported.push('-astc.ktx');
  10476. if (this._caps.s3tc)
  10477. this.texturesSupported.push('-dxt.ktx');
  10478. if (this._caps.pvrtc)
  10479. this.texturesSupported.push('-pvrtc.ktx');
  10480. if (this._caps.etc2)
  10481. this.texturesSupported.push('-etc2.ktx');
  10482. if (this._caps.etc1)
  10483. this.texturesSupported.push('-etc1.ktx');
  10484. if (this._gl.getShaderPrecisionFormat) {
  10485. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10486. if (highp) {
  10487. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10488. }
  10489. }
  10490. // Depth buffer
  10491. this.setDepthBuffer(true);
  10492. this.setDepthFunctionToLessOrEqual();
  10493. this.setDepthWrite(true);
  10494. // Texture maps
  10495. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10496. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10497. this._nextFreeTextureSlots.push(slot);
  10498. }
  10499. };
  10500. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10501. get: function () {
  10502. return this._webGLVersion;
  10503. },
  10504. enumerable: true,
  10505. configurable: true
  10506. });
  10507. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10508. /**
  10509. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10510. */
  10511. get: function () {
  10512. return this._isStencilEnable;
  10513. },
  10514. enumerable: true,
  10515. configurable: true
  10516. });
  10517. Engine.prototype._prepareWorkingCanvas = function () {
  10518. if (this._workingCanvas) {
  10519. return;
  10520. }
  10521. this._workingCanvas = document.createElement("canvas");
  10522. var context = this._workingCanvas.getContext("2d");
  10523. if (context) {
  10524. this._workingContext = context;
  10525. }
  10526. };
  10527. Engine.prototype.resetTextureCache = function () {
  10528. for (var key in this._boundTexturesCache) {
  10529. var boundTexture = this._boundTexturesCache[key];
  10530. if (boundTexture) {
  10531. this._removeDesignatedSlot(boundTexture);
  10532. }
  10533. this._boundTexturesCache[key] = null;
  10534. }
  10535. if (!this.disableTextureBindingOptimization) {
  10536. this._nextFreeTextureSlots = [];
  10537. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10538. this._nextFreeTextureSlots.push(slot);
  10539. }
  10540. }
  10541. this._currentTextureChannel = -1;
  10542. };
  10543. Engine.prototype.isDeterministicLockStep = function () {
  10544. return this._deterministicLockstep;
  10545. };
  10546. Engine.prototype.getLockstepMaxSteps = function () {
  10547. return this._lockstepMaxSteps;
  10548. };
  10549. Engine.prototype.getGlInfo = function () {
  10550. return {
  10551. vendor: this._glVendor,
  10552. renderer: this._glRenderer,
  10553. version: this._glVersion
  10554. };
  10555. };
  10556. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10557. if (useScreen === void 0) { useScreen = false; }
  10558. var viewport = camera.viewport;
  10559. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10560. };
  10561. Engine.prototype.getRenderWidth = function (useScreen) {
  10562. if (useScreen === void 0) { useScreen = false; }
  10563. if (!useScreen && this._currentRenderTarget) {
  10564. return this._currentRenderTarget.width;
  10565. }
  10566. return this._gl.drawingBufferWidth;
  10567. };
  10568. Engine.prototype.getRenderHeight = function (useScreen) {
  10569. if (useScreen === void 0) { useScreen = false; }
  10570. if (!useScreen && this._currentRenderTarget) {
  10571. return this._currentRenderTarget.height;
  10572. }
  10573. return this._gl.drawingBufferHeight;
  10574. };
  10575. Engine.prototype.getRenderingCanvas = function () {
  10576. return this._renderingCanvas;
  10577. };
  10578. Engine.prototype.getRenderingCanvasClientRect = function () {
  10579. if (!this._renderingCanvas) {
  10580. return null;
  10581. }
  10582. return this._renderingCanvas.getBoundingClientRect();
  10583. };
  10584. Engine.prototype.setHardwareScalingLevel = function (level) {
  10585. this._hardwareScalingLevel = level;
  10586. this.resize();
  10587. };
  10588. Engine.prototype.getHardwareScalingLevel = function () {
  10589. return this._hardwareScalingLevel;
  10590. };
  10591. Engine.prototype.getLoadedTexturesCache = function () {
  10592. return this._internalTexturesCache;
  10593. };
  10594. Engine.prototype.getCaps = function () {
  10595. return this._caps;
  10596. };
  10597. Object.defineProperty(Engine.prototype, "drawCalls", {
  10598. /** The number of draw calls submitted last frame */
  10599. get: function () {
  10600. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10601. return 0;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10607. get: function () {
  10608. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10609. return null;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Engine.prototype.getDepthFunction = function () {
  10615. return this._depthCullingState.depthFunc;
  10616. };
  10617. Engine.prototype.setDepthFunction = function (depthFunc) {
  10618. this._depthCullingState.depthFunc = depthFunc;
  10619. };
  10620. Engine.prototype.setDepthFunctionToGreater = function () {
  10621. this._depthCullingState.depthFunc = this._gl.GREATER;
  10622. };
  10623. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10624. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10625. };
  10626. Engine.prototype.setDepthFunctionToLess = function () {
  10627. this._depthCullingState.depthFunc = this._gl.LESS;
  10628. };
  10629. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10630. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10631. };
  10632. Engine.prototype.getStencilBuffer = function () {
  10633. return this._stencilState.stencilTest;
  10634. };
  10635. Engine.prototype.setStencilBuffer = function (enable) {
  10636. this._stencilState.stencilTest = enable;
  10637. };
  10638. Engine.prototype.getStencilMask = function () {
  10639. return this._stencilState.stencilMask;
  10640. };
  10641. Engine.prototype.setStencilMask = function (mask) {
  10642. this._stencilState.stencilMask = mask;
  10643. };
  10644. Engine.prototype.getStencilFunction = function () {
  10645. return this._stencilState.stencilFunc;
  10646. };
  10647. Engine.prototype.getStencilFunctionReference = function () {
  10648. return this._stencilState.stencilFuncRef;
  10649. };
  10650. Engine.prototype.getStencilFunctionMask = function () {
  10651. return this._stencilState.stencilFuncMask;
  10652. };
  10653. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10654. this._stencilState.stencilFunc = stencilFunc;
  10655. };
  10656. Engine.prototype.setStencilFunctionReference = function (reference) {
  10657. this._stencilState.stencilFuncRef = reference;
  10658. };
  10659. Engine.prototype.setStencilFunctionMask = function (mask) {
  10660. this._stencilState.stencilFuncMask = mask;
  10661. };
  10662. Engine.prototype.getStencilOperationFail = function () {
  10663. return this._stencilState.stencilOpStencilFail;
  10664. };
  10665. Engine.prototype.getStencilOperationDepthFail = function () {
  10666. return this._stencilState.stencilOpDepthFail;
  10667. };
  10668. Engine.prototype.getStencilOperationPass = function () {
  10669. return this._stencilState.stencilOpStencilDepthPass;
  10670. };
  10671. Engine.prototype.setStencilOperationFail = function (operation) {
  10672. this._stencilState.stencilOpStencilFail = operation;
  10673. };
  10674. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10675. this._stencilState.stencilOpDepthFail = operation;
  10676. };
  10677. Engine.prototype.setStencilOperationPass = function (operation) {
  10678. this._stencilState.stencilOpStencilDepthPass = operation;
  10679. };
  10680. Engine.prototype.setDitheringState = function (value) {
  10681. if (value) {
  10682. this._gl.enable(this._gl.DITHER);
  10683. }
  10684. else {
  10685. this._gl.disable(this._gl.DITHER);
  10686. }
  10687. };
  10688. Engine.prototype.setRasterizerState = function (value) {
  10689. if (value) {
  10690. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10691. }
  10692. else {
  10693. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10694. }
  10695. };
  10696. /**
  10697. * stop executing a render loop function and remove it from the execution array
  10698. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10699. */
  10700. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10701. if (!renderFunction) {
  10702. this._activeRenderLoops = [];
  10703. return;
  10704. }
  10705. var index = this._activeRenderLoops.indexOf(renderFunction);
  10706. if (index >= 0) {
  10707. this._activeRenderLoops.splice(index, 1);
  10708. }
  10709. };
  10710. Engine.prototype._renderLoop = function () {
  10711. if (!this._contextWasLost) {
  10712. var shouldRender = true;
  10713. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10714. shouldRender = false;
  10715. }
  10716. if (shouldRender) {
  10717. // Start new frame
  10718. this.beginFrame();
  10719. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10720. var renderFunction = this._activeRenderLoops[index];
  10721. renderFunction();
  10722. }
  10723. // Present
  10724. this.endFrame();
  10725. }
  10726. }
  10727. if (this._activeRenderLoops.length > 0) {
  10728. // Register new frame
  10729. var requester = null;
  10730. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10731. requester = this._vrDisplay;
  10732. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10733. }
  10734. else {
  10735. this._renderingQueueLaunched = false;
  10736. }
  10737. };
  10738. /**
  10739. * Register and execute a render loop. The engine can have more than one render function.
  10740. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10741. * @example
  10742. * engine.runRenderLoop(function () {
  10743. * scene.render()
  10744. * })
  10745. */
  10746. Engine.prototype.runRenderLoop = function (renderFunction) {
  10747. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10748. return;
  10749. }
  10750. this._activeRenderLoops.push(renderFunction);
  10751. if (!this._renderingQueueLaunched) {
  10752. this._renderingQueueLaunched = true;
  10753. this._bindedRenderFunction = this._renderLoop.bind(this);
  10754. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10755. }
  10756. };
  10757. /**
  10758. * Toggle full screen mode.
  10759. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10760. * @param {any} options - an options object to be sent to the requestFullscreen function
  10761. */
  10762. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10763. if (this.isFullscreen) {
  10764. BABYLON.Tools.ExitFullscreen();
  10765. }
  10766. else {
  10767. this._pointerLockRequested = requestPointerLock;
  10768. if (this._renderingCanvas) {
  10769. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10770. }
  10771. }
  10772. };
  10773. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10774. if (stencil === void 0) { stencil = false; }
  10775. this.applyStates();
  10776. var mode = 0;
  10777. if (backBuffer && color) {
  10778. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10779. mode |= this._gl.COLOR_BUFFER_BIT;
  10780. }
  10781. if (depth) {
  10782. this._gl.clearDepth(1.0);
  10783. mode |= this._gl.DEPTH_BUFFER_BIT;
  10784. }
  10785. if (stencil) {
  10786. this._gl.clearStencil(0);
  10787. mode |= this._gl.STENCIL_BUFFER_BIT;
  10788. }
  10789. this._gl.clear(mode);
  10790. };
  10791. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10792. var gl = this._gl;
  10793. // Save state
  10794. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10795. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10796. // Change state
  10797. gl.enable(gl.SCISSOR_TEST);
  10798. gl.scissor(x, y, width, height);
  10799. // Clear
  10800. this.clear(clearColor, true, true, true);
  10801. // Restore state
  10802. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10803. if (curScissor === true) {
  10804. gl.enable(gl.SCISSOR_TEST);
  10805. }
  10806. else {
  10807. gl.disable(gl.SCISSOR_TEST);
  10808. }
  10809. };
  10810. /**
  10811. * Set the WebGL's viewport
  10812. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10813. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10814. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10815. */
  10816. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10817. var width = requiredWidth || this.getRenderWidth();
  10818. var height = requiredHeight || this.getRenderHeight();
  10819. var x = viewport.x || 0;
  10820. var y = viewport.y || 0;
  10821. this._cachedViewport = viewport;
  10822. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10823. };
  10824. /**
  10825. * Directly set the WebGL Viewport
  10826. * The x, y, width & height are directly passed to the WebGL call
  10827. * @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.
  10828. */
  10829. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10830. var currentViewport = this._cachedViewport;
  10831. this._cachedViewport = null;
  10832. this._gl.viewport(x, y, width, height);
  10833. return currentViewport;
  10834. };
  10835. Engine.prototype.beginFrame = function () {
  10836. this.onBeginFrameObservable.notifyObservers(this);
  10837. this._measureFps();
  10838. };
  10839. Engine.prototype.endFrame = function () {
  10840. //force a flush in case we are using a bad OS.
  10841. if (this._badOS) {
  10842. this.flushFramebuffer();
  10843. }
  10844. //submit frame to the vr device, if enabled
  10845. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10846. // TODO: We should only submit the frame if we read frameData successfully.
  10847. this._vrDisplay.submitFrame();
  10848. }
  10849. this.onEndFrameObservable.notifyObservers(this);
  10850. };
  10851. /**
  10852. * resize the view according to the canvas' size.
  10853. * @example
  10854. * window.addEventListener("resize", function () {
  10855. * engine.resize();
  10856. * });
  10857. */
  10858. Engine.prototype.resize = function () {
  10859. // We're not resizing the size of the canvas while in VR mode & presenting
  10860. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10861. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10862. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10863. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10864. }
  10865. };
  10866. /**
  10867. * force a specific size of the canvas
  10868. * @param {number} width - the new canvas' width
  10869. * @param {number} height - the new canvas' height
  10870. */
  10871. Engine.prototype.setSize = function (width, height) {
  10872. if (!this._renderingCanvas) {
  10873. return;
  10874. }
  10875. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10876. return;
  10877. }
  10878. this._renderingCanvas.width = width;
  10879. this._renderingCanvas.height = height;
  10880. for (var index = 0; index < this.scenes.length; index++) {
  10881. var scene = this.scenes[index];
  10882. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10883. var cam = scene.cameras[camIndex];
  10884. cam._currentRenderId = 0;
  10885. }
  10886. }
  10887. if (this.onResizeObservable.hasObservers) {
  10888. this.onResizeObservable.notifyObservers(this);
  10889. }
  10890. };
  10891. // WebVR functions
  10892. Engine.prototype.isVRDevicePresent = function () {
  10893. return !!this._vrDisplay;
  10894. };
  10895. Engine.prototype.getVRDevice = function () {
  10896. return this._vrDisplay;
  10897. };
  10898. Engine.prototype.initWebVR = function () {
  10899. var _this = this;
  10900. var notifyObservers = function () {
  10901. var eventArgs = {
  10902. vrDisplay: _this._vrDisplay,
  10903. vrSupported: _this._vrSupported
  10904. };
  10905. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10906. };
  10907. if (!this._onVrDisplayConnect) {
  10908. this._onVrDisplayConnect = function (event) {
  10909. _this._vrDisplay = event.display;
  10910. notifyObservers();
  10911. };
  10912. this._onVrDisplayDisconnect = function () {
  10913. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10914. _this._vrDisplay = undefined;
  10915. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10916. notifyObservers();
  10917. };
  10918. this._onVrDisplayPresentChange = function () {
  10919. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10920. };
  10921. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10922. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10923. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10924. }
  10925. this._getVRDisplays(notifyObservers);
  10926. return this.onVRDisplayChangedObservable;
  10927. };
  10928. Engine.prototype.enableVR = function () {
  10929. var _this = this;
  10930. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10931. var onResolved = function () {
  10932. _this.onVRRequestPresentComplete.notifyObservers(true);
  10933. _this._onVRFullScreenTriggered();
  10934. };
  10935. var onRejected = function () {
  10936. _this.onVRRequestPresentComplete.notifyObservers(false);
  10937. };
  10938. this.onVRRequestPresentStart.notifyObservers(this);
  10939. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10940. }
  10941. };
  10942. Engine.prototype.disableVR = function () {
  10943. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10944. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10945. }
  10946. };
  10947. Engine.prototype._getVRDisplays = function (callback) {
  10948. var _this = this;
  10949. var getWebVRDevices = function (devices) {
  10950. _this._vrSupported = true;
  10951. // note that devices may actually be an empty array. This is fine;
  10952. // we expect this._vrDisplay to be undefined in this case.
  10953. return _this._vrDisplay = devices[0];
  10954. };
  10955. if (navigator.getVRDisplays) {
  10956. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10957. // TODO: System CANNOT support WebVR, despite API presence.
  10958. _this._vrSupported = false;
  10959. callback();
  10960. });
  10961. }
  10962. else {
  10963. // TODO: Browser does not support WebVR
  10964. this._vrDisplay = undefined;
  10965. this._vrSupported = false;
  10966. callback();
  10967. }
  10968. };
  10969. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10970. if (this._currentRenderTarget) {
  10971. this.unBindFramebuffer(this._currentRenderTarget);
  10972. }
  10973. this._currentRenderTarget = texture;
  10974. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10975. var gl = this._gl;
  10976. if (texture.isCube) {
  10977. if (faceIndex === undefined) {
  10978. faceIndex = 0;
  10979. }
  10980. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10981. }
  10982. if (this._cachedViewport && !forceFullscreenViewport) {
  10983. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10984. }
  10985. else {
  10986. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10987. }
  10988. this.wipeCaches();
  10989. };
  10990. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10991. if (this._currentFramebuffer !== framebuffer) {
  10992. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10993. this._currentFramebuffer = framebuffer;
  10994. }
  10995. };
  10996. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10997. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10998. this._currentRenderTarget = null;
  10999. // If MSAA, we need to bitblt back to main texture
  11000. var gl = this._gl;
  11001. if (texture._MSAAFramebuffer) {
  11002. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11003. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11004. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11005. }
  11006. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11007. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11008. gl.generateMipmap(gl.TEXTURE_2D);
  11009. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11010. }
  11011. if (onBeforeUnbind) {
  11012. if (texture._MSAAFramebuffer) {
  11013. // Bind the correct framebuffer
  11014. this.bindUnboundFramebuffer(texture._framebuffer);
  11015. }
  11016. onBeforeUnbind();
  11017. }
  11018. this.bindUnboundFramebuffer(null);
  11019. };
  11020. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11021. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11022. this._currentRenderTarget = null;
  11023. // If MSAA, we need to bitblt back to main texture
  11024. var gl = this._gl;
  11025. if (textures[0]._MSAAFramebuffer) {
  11026. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11027. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11028. var attachments = textures[0]._attachments;
  11029. if (!attachments) {
  11030. attachments = new Array(textures.length);
  11031. textures[0]._attachments = attachments;
  11032. }
  11033. for (var i = 0; i < textures.length; i++) {
  11034. var texture = textures[i];
  11035. for (var j = 0; j < attachments.length; j++) {
  11036. attachments[j] = gl.NONE;
  11037. }
  11038. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11039. gl.readBuffer(attachments[i]);
  11040. gl.drawBuffers(attachments);
  11041. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11042. }
  11043. for (var i = 0; i < attachments.length; i++) {
  11044. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11045. }
  11046. gl.drawBuffers(attachments);
  11047. }
  11048. for (var i = 0; i < textures.length; i++) {
  11049. var texture = textures[i];
  11050. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11051. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11052. gl.generateMipmap(gl.TEXTURE_2D);
  11053. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11054. }
  11055. }
  11056. if (onBeforeUnbind) {
  11057. if (textures[0]._MSAAFramebuffer) {
  11058. // Bind the correct framebuffer
  11059. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11060. }
  11061. onBeforeUnbind();
  11062. }
  11063. this.bindUnboundFramebuffer(null);
  11064. };
  11065. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11066. if (texture.generateMipMaps) {
  11067. var gl = this._gl;
  11068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11069. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11071. }
  11072. };
  11073. Engine.prototype.flushFramebuffer = function () {
  11074. this._gl.flush();
  11075. };
  11076. Engine.prototype.restoreDefaultFramebuffer = function () {
  11077. if (this._currentRenderTarget) {
  11078. this.unBindFramebuffer(this._currentRenderTarget);
  11079. }
  11080. else {
  11081. this.bindUnboundFramebuffer(null);
  11082. }
  11083. if (this._cachedViewport) {
  11084. this.setViewport(this._cachedViewport);
  11085. }
  11086. this.wipeCaches();
  11087. };
  11088. // UBOs
  11089. Engine.prototype.createUniformBuffer = function (elements) {
  11090. var ubo = this._gl.createBuffer();
  11091. if (!ubo) {
  11092. throw new Error("Unable to create uniform buffer");
  11093. }
  11094. this.bindUniformBuffer(ubo);
  11095. if (elements instanceof Float32Array) {
  11096. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11097. }
  11098. else {
  11099. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11100. }
  11101. this.bindUniformBuffer(null);
  11102. ubo.references = 1;
  11103. return ubo;
  11104. };
  11105. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11106. var ubo = this._gl.createBuffer();
  11107. if (!ubo) {
  11108. throw new Error("Unable to create dynamic uniform buffer");
  11109. }
  11110. this.bindUniformBuffer(ubo);
  11111. if (elements instanceof Float32Array) {
  11112. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11113. }
  11114. else {
  11115. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11116. }
  11117. this.bindUniformBuffer(null);
  11118. ubo.references = 1;
  11119. return ubo;
  11120. };
  11121. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11122. this.bindUniformBuffer(uniformBuffer);
  11123. if (offset === undefined) {
  11124. offset = 0;
  11125. }
  11126. if (count === undefined) {
  11127. if (elements instanceof Float32Array) {
  11128. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11129. }
  11130. else {
  11131. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11132. }
  11133. }
  11134. else {
  11135. if (elements instanceof Float32Array) {
  11136. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11137. }
  11138. else {
  11139. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11140. }
  11141. }
  11142. this.bindUniformBuffer(null);
  11143. };
  11144. // VBOs
  11145. Engine.prototype._resetVertexBufferBinding = function () {
  11146. this.bindArrayBuffer(null);
  11147. this._cachedVertexBuffers = null;
  11148. };
  11149. Engine.prototype.createVertexBuffer = function (vertices) {
  11150. var vbo = this._gl.createBuffer();
  11151. if (!vbo) {
  11152. throw new Error("Unable to create vertex buffer");
  11153. }
  11154. this.bindArrayBuffer(vbo);
  11155. if (vertices instanceof Float32Array) {
  11156. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11157. }
  11158. else {
  11159. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11160. }
  11161. this._resetVertexBufferBinding();
  11162. vbo.references = 1;
  11163. return vbo;
  11164. };
  11165. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11166. var vbo = this._gl.createBuffer();
  11167. if (!vbo) {
  11168. throw new Error("Unable to create dynamic vertex buffer");
  11169. }
  11170. this.bindArrayBuffer(vbo);
  11171. if (vertices instanceof Float32Array) {
  11172. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11173. }
  11174. else {
  11175. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11176. }
  11177. this._resetVertexBufferBinding();
  11178. vbo.references = 1;
  11179. return vbo;
  11180. };
  11181. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11182. if (offset === void 0) { offset = 0; }
  11183. // Force cache update
  11184. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11185. this.bindIndexBuffer(indexBuffer);
  11186. var arrayBuffer;
  11187. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11188. arrayBuffer = indices;
  11189. }
  11190. else {
  11191. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11192. }
  11193. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11194. this._resetIndexBufferBinding();
  11195. };
  11196. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11197. this.bindArrayBuffer(vertexBuffer);
  11198. if (offset === undefined) {
  11199. offset = 0;
  11200. }
  11201. if (count === undefined) {
  11202. if (vertices instanceof Float32Array) {
  11203. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11204. }
  11205. else {
  11206. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11207. }
  11208. }
  11209. else {
  11210. if (vertices instanceof Float32Array) {
  11211. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11212. }
  11213. else {
  11214. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11215. }
  11216. }
  11217. this._resetVertexBufferBinding();
  11218. };
  11219. Engine.prototype._resetIndexBufferBinding = function () {
  11220. this.bindIndexBuffer(null);
  11221. this._cachedIndexBuffer = null;
  11222. };
  11223. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11224. var vbo = this._gl.createBuffer();
  11225. if (!vbo) {
  11226. throw new Error("Unable to create index buffer");
  11227. }
  11228. this.bindIndexBuffer(vbo);
  11229. // Check for 32 bits indices
  11230. var arrayBuffer;
  11231. var need32Bits = false;
  11232. if (indices instanceof Uint16Array) {
  11233. arrayBuffer = indices;
  11234. }
  11235. else {
  11236. //check 32 bit support
  11237. if (this._caps.uintIndices) {
  11238. if (indices instanceof Uint32Array) {
  11239. arrayBuffer = indices;
  11240. need32Bits = true;
  11241. }
  11242. else {
  11243. //number[] or Int32Array, check if 32 bit is necessary
  11244. for (var index = 0; index < indices.length; index++) {
  11245. if (indices[index] > 65535) {
  11246. need32Bits = true;
  11247. break;
  11248. }
  11249. }
  11250. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11251. }
  11252. }
  11253. else {
  11254. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11255. arrayBuffer = new Uint16Array(indices);
  11256. }
  11257. }
  11258. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11259. this._resetIndexBufferBinding();
  11260. vbo.references = 1;
  11261. vbo.is32Bits = need32Bits;
  11262. return vbo;
  11263. };
  11264. Engine.prototype.bindArrayBuffer = function (buffer) {
  11265. if (!this._vaoRecordInProgress) {
  11266. this._unbindVertexArrayObject();
  11267. }
  11268. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11269. };
  11270. Engine.prototype.bindUniformBuffer = function (buffer) {
  11271. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11272. };
  11273. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11274. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11275. };
  11276. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11277. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11278. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11279. };
  11280. ;
  11281. Engine.prototype.bindIndexBuffer = function (buffer) {
  11282. if (!this._vaoRecordInProgress) {
  11283. this._unbindVertexArrayObject();
  11284. }
  11285. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11286. };
  11287. Engine.prototype.bindBuffer = function (buffer, target) {
  11288. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11289. this._gl.bindBuffer(target, buffer);
  11290. this._currentBoundBuffer[target] = buffer;
  11291. }
  11292. };
  11293. Engine.prototype.updateArrayBuffer = function (data) {
  11294. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11295. };
  11296. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11297. var pointer = this._currentBufferPointers[indx];
  11298. var changed = false;
  11299. if (!pointer.active) {
  11300. changed = true;
  11301. pointer.active = true;
  11302. pointer.index = indx;
  11303. pointer.size = size;
  11304. pointer.type = type;
  11305. pointer.normalized = normalized;
  11306. pointer.stride = stride;
  11307. pointer.offset = offset;
  11308. pointer.buffer = buffer;
  11309. }
  11310. else {
  11311. if (pointer.buffer !== buffer) {
  11312. pointer.buffer = buffer;
  11313. changed = true;
  11314. }
  11315. if (pointer.size !== size) {
  11316. pointer.size = size;
  11317. changed = true;
  11318. }
  11319. if (pointer.type !== type) {
  11320. pointer.type = type;
  11321. changed = true;
  11322. }
  11323. if (pointer.normalized !== normalized) {
  11324. pointer.normalized = normalized;
  11325. changed = true;
  11326. }
  11327. if (pointer.stride !== stride) {
  11328. pointer.stride = stride;
  11329. changed = true;
  11330. }
  11331. if (pointer.offset !== offset) {
  11332. pointer.offset = offset;
  11333. changed = true;
  11334. }
  11335. }
  11336. if (changed || this._vaoRecordInProgress) {
  11337. this.bindArrayBuffer(buffer);
  11338. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11339. }
  11340. };
  11341. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11342. if (indexBuffer == null) {
  11343. return;
  11344. }
  11345. if (this._cachedIndexBuffer !== indexBuffer) {
  11346. this._cachedIndexBuffer = indexBuffer;
  11347. this.bindIndexBuffer(indexBuffer);
  11348. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11349. }
  11350. };
  11351. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11352. var attributes = effect.getAttributesNames();
  11353. if (!this._vaoRecordInProgress) {
  11354. this._unbindVertexArrayObject();
  11355. }
  11356. this.unbindAllAttributes();
  11357. for (var index = 0; index < attributes.length; index++) {
  11358. var order = effect.getAttributeLocation(index);
  11359. if (order >= 0) {
  11360. var vertexBuffer = vertexBuffers[attributes[index]];
  11361. if (!vertexBuffer) {
  11362. continue;
  11363. }
  11364. this._gl.enableVertexAttribArray(order);
  11365. if (!this._vaoRecordInProgress) {
  11366. this._vertexAttribArraysEnabled[order] = true;
  11367. }
  11368. var buffer = vertexBuffer.getBuffer();
  11369. if (buffer) {
  11370. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11371. if (vertexBuffer.getIsInstanced()) {
  11372. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11373. if (!this._vaoRecordInProgress) {
  11374. this._currentInstanceLocations.push(order);
  11375. this._currentInstanceBuffers.push(buffer);
  11376. }
  11377. }
  11378. }
  11379. }
  11380. }
  11381. };
  11382. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11383. var vao = this._gl.createVertexArray();
  11384. this._vaoRecordInProgress = true;
  11385. this._gl.bindVertexArray(vao);
  11386. this._mustWipeVertexAttributes = true;
  11387. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11388. this.bindIndexBuffer(indexBuffer);
  11389. this._vaoRecordInProgress = false;
  11390. this._gl.bindVertexArray(null);
  11391. return vao;
  11392. };
  11393. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11394. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11395. this._cachedVertexArrayObject = vertexArrayObject;
  11396. this._gl.bindVertexArray(vertexArrayObject);
  11397. this._cachedVertexBuffers = null;
  11398. this._cachedIndexBuffer = null;
  11399. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11400. this._mustWipeVertexAttributes = true;
  11401. }
  11402. };
  11403. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11404. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11405. this._cachedVertexBuffers = vertexBuffer;
  11406. this._cachedEffectForVertexBuffers = effect;
  11407. var attributesCount = effect.getAttributesCount();
  11408. this._unbindVertexArrayObject();
  11409. this.unbindAllAttributes();
  11410. var offset = 0;
  11411. for (var index = 0; index < attributesCount; index++) {
  11412. if (index < vertexDeclaration.length) {
  11413. var order = effect.getAttributeLocation(index);
  11414. if (order >= 0) {
  11415. this._gl.enableVertexAttribArray(order);
  11416. this._vertexAttribArraysEnabled[order] = true;
  11417. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11418. }
  11419. offset += vertexDeclaration[index] * 4;
  11420. }
  11421. }
  11422. }
  11423. this._bindIndexBufferWithCache(indexBuffer);
  11424. };
  11425. Engine.prototype._unbindVertexArrayObject = function () {
  11426. if (!this._cachedVertexArrayObject) {
  11427. return;
  11428. }
  11429. this._cachedVertexArrayObject = null;
  11430. this._gl.bindVertexArray(null);
  11431. };
  11432. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11433. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11434. this._cachedVertexBuffers = vertexBuffers;
  11435. this._cachedEffectForVertexBuffers = effect;
  11436. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11437. }
  11438. this._bindIndexBufferWithCache(indexBuffer);
  11439. };
  11440. Engine.prototype.unbindInstanceAttributes = function () {
  11441. var boundBuffer;
  11442. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11443. var instancesBuffer = this._currentInstanceBuffers[i];
  11444. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11445. boundBuffer = instancesBuffer;
  11446. this.bindArrayBuffer(instancesBuffer);
  11447. }
  11448. var offsetLocation = this._currentInstanceLocations[i];
  11449. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11450. }
  11451. this._currentInstanceBuffers.length = 0;
  11452. this._currentInstanceLocations.length = 0;
  11453. };
  11454. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11455. this._gl.deleteVertexArray(vao);
  11456. };
  11457. Engine.prototype._releaseBuffer = function (buffer) {
  11458. buffer.references--;
  11459. if (buffer.references === 0) {
  11460. this._gl.deleteBuffer(buffer);
  11461. return true;
  11462. }
  11463. return false;
  11464. };
  11465. Engine.prototype.createInstancesBuffer = function (capacity) {
  11466. var buffer = this._gl.createBuffer();
  11467. if (!buffer) {
  11468. throw new Error("Unable to create instance buffer");
  11469. }
  11470. buffer.capacity = capacity;
  11471. this.bindArrayBuffer(buffer);
  11472. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11473. return buffer;
  11474. };
  11475. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11476. this._gl.deleteBuffer(buffer);
  11477. };
  11478. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11479. this.bindArrayBuffer(instancesBuffer);
  11480. if (data) {
  11481. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11482. }
  11483. if (offsetLocations[0].index !== undefined) {
  11484. var stride = 0;
  11485. for (var i = 0; i < offsetLocations.length; i++) {
  11486. var ai = offsetLocations[i];
  11487. stride += ai.attributeSize * 4;
  11488. }
  11489. for (var i = 0; i < offsetLocations.length; i++) {
  11490. var ai = offsetLocations[i];
  11491. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11492. this._gl.enableVertexAttribArray(ai.index);
  11493. this._vertexAttribArraysEnabled[ai.index] = true;
  11494. }
  11495. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11496. this._gl.vertexAttribDivisor(ai.index, 1);
  11497. this._currentInstanceLocations.push(ai.index);
  11498. this._currentInstanceBuffers.push(instancesBuffer);
  11499. }
  11500. }
  11501. else {
  11502. for (var index = 0; index < 4; index++) {
  11503. var offsetLocation = offsetLocations[index];
  11504. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11505. this._gl.enableVertexAttribArray(offsetLocation);
  11506. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11507. }
  11508. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11509. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11510. this._currentInstanceLocations.push(offsetLocation);
  11511. this._currentInstanceBuffers.push(instancesBuffer);
  11512. }
  11513. }
  11514. };
  11515. Engine.prototype.applyStates = function () {
  11516. this._depthCullingState.apply(this._gl);
  11517. this._stencilState.apply(this._gl);
  11518. this._alphaState.apply(this._gl);
  11519. };
  11520. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11521. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11522. };
  11523. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11524. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11525. };
  11526. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11527. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11528. };
  11529. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11530. // Apply states
  11531. this.applyStates();
  11532. this._drawCalls.addCount(1, false);
  11533. // Render
  11534. var drawMode = this.DrawMode(fillMode);
  11535. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11536. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11537. if (instancesCount) {
  11538. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11539. }
  11540. else {
  11541. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11542. }
  11543. };
  11544. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11545. // Apply states
  11546. this.applyStates();
  11547. this._drawCalls.addCount(1, false);
  11548. var drawMode = this.DrawMode(fillMode);
  11549. if (instancesCount) {
  11550. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11551. }
  11552. else {
  11553. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11554. }
  11555. };
  11556. Engine.prototype.DrawMode = function (fillMode) {
  11557. switch (fillMode) {
  11558. // Triangle views
  11559. case BABYLON.Material.TriangleFillMode:
  11560. return this._gl.TRIANGLES;
  11561. case BABYLON.Material.PointFillMode:
  11562. return this._gl.POINTS;
  11563. case BABYLON.Material.WireFrameFillMode:
  11564. return this._gl.LINES;
  11565. // Draw modes
  11566. case BABYLON.Material.PointListDrawMode:
  11567. return this._gl.POINTS;
  11568. case BABYLON.Material.LineListDrawMode:
  11569. return this._gl.LINES;
  11570. case BABYLON.Material.LineLoopDrawMode:
  11571. return this._gl.LINE_LOOP;
  11572. case BABYLON.Material.LineStripDrawMode:
  11573. return this._gl.LINE_STRIP;
  11574. case BABYLON.Material.TriangleStripDrawMode:
  11575. return this._gl.TRIANGLE_STRIP;
  11576. case BABYLON.Material.TriangleFanDrawMode:
  11577. return this._gl.TRIANGLE_FAN;
  11578. default:
  11579. return this._gl.TRIANGLES;
  11580. }
  11581. };
  11582. // Shaders
  11583. Engine.prototype._releaseEffect = function (effect) {
  11584. if (this._compiledEffects[effect._key]) {
  11585. delete this._compiledEffects[effect._key];
  11586. this._deleteProgram(effect.getProgram());
  11587. }
  11588. };
  11589. Engine.prototype._deleteProgram = function (program) {
  11590. if (program) {
  11591. program.__SPECTOR_rebuildProgram = null;
  11592. if (program.transformFeedback) {
  11593. this.deleteTransformFeedback(program.transformFeedback);
  11594. program.transformFeedback = null;
  11595. }
  11596. this._gl.deleteProgram(program);
  11597. }
  11598. };
  11599. /**
  11600. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11601. * @param samplers An array of string used to represent textures
  11602. */
  11603. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11604. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11605. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11606. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11607. if (this._compiledEffects[name]) {
  11608. var compiledEffect = this._compiledEffects[name];
  11609. if (onCompiled && compiledEffect.isReady()) {
  11610. onCompiled(compiledEffect);
  11611. }
  11612. return compiledEffect;
  11613. }
  11614. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11615. effect._key = name;
  11616. this._compiledEffects[name] = effect;
  11617. return effect;
  11618. };
  11619. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11620. if (uniformsNames === void 0) { uniformsNames = []; }
  11621. if (samplers === void 0) { samplers = []; }
  11622. if (defines === void 0) { defines = ""; }
  11623. return this.createEffect({
  11624. vertex: "particles",
  11625. fragmentElement: fragmentName
  11626. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11627. };
  11628. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11629. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11630. context = context || this._gl;
  11631. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11632. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11633. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11634. };
  11635. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11636. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11637. context = context || this._gl;
  11638. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11639. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11640. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11641. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11642. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11643. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11644. return program;
  11645. };
  11646. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11647. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11648. var shaderProgram = context.createProgram();
  11649. if (!shaderProgram) {
  11650. throw new Error("Unable to create program");
  11651. }
  11652. context.attachShader(shaderProgram, vertexShader);
  11653. context.attachShader(shaderProgram, fragmentShader);
  11654. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11655. var transformFeedback = this.createTransformFeedback();
  11656. this.bindTransformFeedback(transformFeedback);
  11657. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11658. shaderProgram.transformFeedback = transformFeedback;
  11659. }
  11660. context.linkProgram(shaderProgram);
  11661. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11662. this.bindTransformFeedback(null);
  11663. }
  11664. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11665. if (!linked) {
  11666. context.validateProgram(shaderProgram);
  11667. var error = context.getProgramInfoLog(shaderProgram);
  11668. if (error) {
  11669. throw new Error(error);
  11670. }
  11671. }
  11672. context.deleteShader(vertexShader);
  11673. context.deleteShader(fragmentShader);
  11674. return shaderProgram;
  11675. };
  11676. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11677. var results = new Array();
  11678. for (var index = 0; index < uniformsNames.length; index++) {
  11679. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11680. }
  11681. return results;
  11682. };
  11683. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11684. var results = [];
  11685. for (var index = 0; index < attributesNames.length; index++) {
  11686. try {
  11687. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11688. }
  11689. catch (e) {
  11690. results.push(-1);
  11691. }
  11692. }
  11693. return results;
  11694. };
  11695. Engine.prototype.enableEffect = function (effect) {
  11696. if (!effect) {
  11697. return;
  11698. }
  11699. // Use program
  11700. this.bindSamplers(effect);
  11701. this._currentEffect = effect;
  11702. if (effect.onBind) {
  11703. effect.onBind(effect);
  11704. }
  11705. effect.onBindObservable.notifyObservers(effect);
  11706. };
  11707. Engine.prototype.setIntArray = function (uniform, array) {
  11708. if (!uniform)
  11709. return;
  11710. this._gl.uniform1iv(uniform, array);
  11711. };
  11712. Engine.prototype.setIntArray2 = function (uniform, array) {
  11713. if (!uniform || array.length % 2 !== 0)
  11714. return;
  11715. this._gl.uniform2iv(uniform, array);
  11716. };
  11717. Engine.prototype.setIntArray3 = function (uniform, array) {
  11718. if (!uniform || array.length % 3 !== 0)
  11719. return;
  11720. this._gl.uniform3iv(uniform, array);
  11721. };
  11722. Engine.prototype.setIntArray4 = function (uniform, array) {
  11723. if (!uniform || array.length % 4 !== 0)
  11724. return;
  11725. this._gl.uniform4iv(uniform, array);
  11726. };
  11727. Engine.prototype.setFloatArray = function (uniform, array) {
  11728. if (!uniform)
  11729. return;
  11730. this._gl.uniform1fv(uniform, array);
  11731. };
  11732. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11733. if (!uniform || array.length % 2 !== 0)
  11734. return;
  11735. this._gl.uniform2fv(uniform, array);
  11736. };
  11737. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11738. if (!uniform || array.length % 3 !== 0)
  11739. return;
  11740. this._gl.uniform3fv(uniform, array);
  11741. };
  11742. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11743. if (!uniform || array.length % 4 !== 0)
  11744. return;
  11745. this._gl.uniform4fv(uniform, array);
  11746. };
  11747. Engine.prototype.setArray = function (uniform, array) {
  11748. if (!uniform)
  11749. return;
  11750. this._gl.uniform1fv(uniform, array);
  11751. };
  11752. Engine.prototype.setArray2 = function (uniform, array) {
  11753. if (!uniform || array.length % 2 !== 0)
  11754. return;
  11755. this._gl.uniform2fv(uniform, array);
  11756. };
  11757. Engine.prototype.setArray3 = function (uniform, array) {
  11758. if (!uniform || array.length % 3 !== 0)
  11759. return;
  11760. this._gl.uniform3fv(uniform, array);
  11761. };
  11762. Engine.prototype.setArray4 = function (uniform, array) {
  11763. if (!uniform || array.length % 4 !== 0)
  11764. return;
  11765. this._gl.uniform4fv(uniform, array);
  11766. };
  11767. Engine.prototype.setMatrices = function (uniform, matrices) {
  11768. if (!uniform)
  11769. return;
  11770. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11771. };
  11772. Engine.prototype.setMatrix = function (uniform, matrix) {
  11773. if (!uniform)
  11774. return;
  11775. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11776. };
  11777. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11778. if (!uniform)
  11779. return;
  11780. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11781. };
  11782. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11783. if (!uniform)
  11784. return;
  11785. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11786. };
  11787. Engine.prototype.setInt = function (uniform, value) {
  11788. if (!uniform)
  11789. return;
  11790. this._gl.uniform1i(uniform, value);
  11791. };
  11792. Engine.prototype.setFloat = function (uniform, value) {
  11793. if (!uniform)
  11794. return;
  11795. this._gl.uniform1f(uniform, value);
  11796. };
  11797. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11798. if (!uniform)
  11799. return;
  11800. this._gl.uniform2f(uniform, x, y);
  11801. };
  11802. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11803. if (!uniform)
  11804. return;
  11805. this._gl.uniform3f(uniform, x, y, z);
  11806. };
  11807. Engine.prototype.setBool = function (uniform, bool) {
  11808. if (!uniform)
  11809. return;
  11810. this._gl.uniform1i(uniform, bool);
  11811. };
  11812. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11813. if (!uniform)
  11814. return;
  11815. this._gl.uniform4f(uniform, x, y, z, w);
  11816. };
  11817. Engine.prototype.setColor3 = function (uniform, color3) {
  11818. if (!uniform)
  11819. return;
  11820. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11821. };
  11822. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11823. if (!uniform)
  11824. return;
  11825. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11826. };
  11827. // States
  11828. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11829. if (zOffset === void 0) { zOffset = 0; }
  11830. if (reverseSide === void 0) { reverseSide = false; }
  11831. // Culling
  11832. if (this._depthCullingState.cull !== culling || force) {
  11833. this._depthCullingState.cull = culling;
  11834. }
  11835. // Cull face
  11836. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11837. if (this._depthCullingState.cullFace !== cullFace || force) {
  11838. this._depthCullingState.cullFace = cullFace;
  11839. }
  11840. // Z offset
  11841. this.setZOffset(zOffset);
  11842. // Front face
  11843. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11844. if (this._depthCullingState.frontFace !== frontFace || force) {
  11845. this._depthCullingState.frontFace = frontFace;
  11846. }
  11847. };
  11848. Engine.prototype.setZOffset = function (value) {
  11849. this._depthCullingState.zOffset = value;
  11850. };
  11851. Engine.prototype.getZOffset = function () {
  11852. return this._depthCullingState.zOffset;
  11853. };
  11854. Engine.prototype.setDepthBuffer = function (enable) {
  11855. this._depthCullingState.depthTest = enable;
  11856. };
  11857. Engine.prototype.getDepthWrite = function () {
  11858. return this._depthCullingState.depthMask;
  11859. };
  11860. Engine.prototype.setDepthWrite = function (enable) {
  11861. this._depthCullingState.depthMask = enable;
  11862. };
  11863. Engine.prototype.setColorWrite = function (enable) {
  11864. this._gl.colorMask(enable, enable, enable, enable);
  11865. this._colorWrite = enable;
  11866. };
  11867. Engine.prototype.getColorWrite = function () {
  11868. return this._colorWrite;
  11869. };
  11870. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11871. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11872. };
  11873. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11874. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11875. if (this._alphaMode === mode) {
  11876. return;
  11877. }
  11878. switch (mode) {
  11879. case Engine.ALPHA_DISABLE:
  11880. this._alphaState.alphaBlend = false;
  11881. break;
  11882. case Engine.ALPHA_PREMULTIPLIED:
  11883. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11884. this._alphaState.alphaBlend = true;
  11885. break;
  11886. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11887. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11888. this._alphaState.alphaBlend = true;
  11889. break;
  11890. case Engine.ALPHA_COMBINE:
  11891. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11892. this._alphaState.alphaBlend = true;
  11893. break;
  11894. case Engine.ALPHA_ONEONE:
  11895. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11896. this._alphaState.alphaBlend = true;
  11897. break;
  11898. case Engine.ALPHA_ADD:
  11899. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11900. this._alphaState.alphaBlend = true;
  11901. break;
  11902. case Engine.ALPHA_SUBTRACT:
  11903. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11904. this._alphaState.alphaBlend = true;
  11905. break;
  11906. case Engine.ALPHA_MULTIPLY:
  11907. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11908. this._alphaState.alphaBlend = true;
  11909. break;
  11910. case Engine.ALPHA_MAXIMIZED:
  11911. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11912. this._alphaState.alphaBlend = true;
  11913. break;
  11914. case Engine.ALPHA_INTERPOLATE:
  11915. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11916. this._alphaState.alphaBlend = true;
  11917. break;
  11918. case Engine.ALPHA_SCREENMODE:
  11919. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11920. this._alphaState.alphaBlend = true;
  11921. break;
  11922. }
  11923. if (!noDepthWriteChange) {
  11924. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11925. }
  11926. this._alphaMode = mode;
  11927. };
  11928. Engine.prototype.getAlphaMode = function () {
  11929. return this._alphaMode;
  11930. };
  11931. // Textures
  11932. Engine.prototype.wipeCaches = function (bruteForce) {
  11933. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11934. return;
  11935. }
  11936. this._currentEffect = null;
  11937. // 6/8/2017: deltakosh: Should not be required anymore.
  11938. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11939. if (bruteForce) {
  11940. this.resetTextureCache();
  11941. this._currentProgram = null;
  11942. this._stencilState.reset();
  11943. this._depthCullingState.reset();
  11944. this.setDepthFunctionToLessOrEqual();
  11945. this._alphaState.reset();
  11946. }
  11947. this._resetVertexBufferBinding();
  11948. this._cachedIndexBuffer = null;
  11949. this._cachedEffectForVertexBuffers = null;
  11950. this._unbindVertexArrayObject();
  11951. this.bindIndexBuffer(null);
  11952. };
  11953. /**
  11954. * Set the compressed texture format to use, based on the formats you have, and the formats
  11955. * supported by the hardware / browser.
  11956. *
  11957. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11958. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11959. * to API arguments needed to compressed textures. This puts the burden on the container
  11960. * generator to house the arcane code for determining these for current & future formats.
  11961. *
  11962. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11963. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11964. *
  11965. * Note: The result of this call is not taken into account when a texture is base64.
  11966. *
  11967. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11968. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11969. *
  11970. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11971. * @returns The extension selected.
  11972. */
  11973. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11974. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11975. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11976. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11977. return this._textureFormatInUse = this._texturesSupported[i];
  11978. }
  11979. }
  11980. }
  11981. // actively set format to nothing, to allow this to be called more than once
  11982. // and possibly fail the 2nd time
  11983. this._textureFormatInUse = null;
  11984. return null;
  11985. };
  11986. Engine.prototype._createTexture = function () {
  11987. var texture = this._gl.createTexture();
  11988. if (!texture) {
  11989. throw new Error("Unable to create texture");
  11990. }
  11991. return texture;
  11992. };
  11993. /**
  11994. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11995. * @param {string} urlArg- This contains one of the following:
  11996. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11997. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11998. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11999. *
  12000. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12001. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12002. * @param {Scene} scene- Needed for loading to the correct scene.
  12003. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12004. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12005. * @param {callback} onError- Optional callback to be called upon failure.
  12006. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12007. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12008. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12009. *
  12010. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12011. */
  12012. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12013. var _this = this;
  12014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12015. if (onLoad === void 0) { onLoad = null; }
  12016. if (onError === void 0) { onError = null; }
  12017. if (buffer === void 0) { buffer = null; }
  12018. if (fallBack === void 0) { fallBack = null; }
  12019. if (format === void 0) { format = null; }
  12020. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12021. var fromData = url.substr(0, 5) === "data:";
  12022. var fromBlob = url.substr(0, 5) === "blob:";
  12023. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12024. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12025. // establish the file extension, if possible
  12026. var lastDot = url.lastIndexOf('.');
  12027. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12028. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12029. var isTGA = (extension.indexOf(".tga") === 0);
  12030. // determine if a ktx file should be substituted
  12031. var isKTX = false;
  12032. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12033. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12034. isKTX = true;
  12035. }
  12036. if (scene) {
  12037. scene._addPendingData(texture);
  12038. }
  12039. texture.url = url;
  12040. texture.generateMipMaps = !noMipmap;
  12041. texture.samplingMode = samplingMode;
  12042. texture.invertY = invertY;
  12043. if (!this._doNotHandleContextLost) {
  12044. // Keep a link to the buffer only if we plan to handle context lost
  12045. texture._buffer = buffer;
  12046. }
  12047. var onLoadObserver = null;
  12048. if (onLoad && !fallBack) {
  12049. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12050. }
  12051. if (!fallBack)
  12052. this._internalTexturesCache.push(texture);
  12053. var onerror = function (message, exception) {
  12054. if (scene) {
  12055. scene._removePendingData(texture);
  12056. }
  12057. if (onLoadObserver) {
  12058. texture.onLoadedObservable.remove(onLoadObserver);
  12059. }
  12060. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12061. if (isKTX) {
  12062. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12063. }
  12064. else if (BABYLON.Tools.UseFallbackTexture) {
  12065. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12066. }
  12067. if (onError) {
  12068. onError(message || "Unknown error", exception);
  12069. }
  12070. };
  12071. var callback = null;
  12072. // processing for non-image formats
  12073. if (isKTX || isTGA || isDDS) {
  12074. if (isKTX) {
  12075. callback = function (data) {
  12076. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12077. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12078. ktx.uploadLevels(_this._gl, !noMipmap);
  12079. return false;
  12080. }, samplingMode);
  12081. };
  12082. }
  12083. else if (isTGA) {
  12084. callback = function (arrayBuffer) {
  12085. var data = new Uint8Array(arrayBuffer);
  12086. var header = BABYLON.TGATools.GetTGAHeader(data);
  12087. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12088. BABYLON.TGATools.UploadContent(_this._gl, data);
  12089. return false;
  12090. }, samplingMode);
  12091. };
  12092. }
  12093. else if (isDDS) {
  12094. callback = function (data) {
  12095. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12096. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12097. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12098. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12099. return false;
  12100. }, samplingMode);
  12101. };
  12102. }
  12103. if (!buffer) {
  12104. this._loadFile(url, function (data) {
  12105. if (callback) {
  12106. callback(data);
  12107. }
  12108. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12109. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12110. });
  12111. }
  12112. else {
  12113. if (callback) {
  12114. callback(buffer);
  12115. }
  12116. }
  12117. // image format processing
  12118. }
  12119. else {
  12120. var onload = function (img) {
  12121. if (fromBlob && !_this._doNotHandleContextLost) {
  12122. // We need to store the image if we need to rebuild the texture
  12123. // in case of a webgl context lost
  12124. texture._buffer = img;
  12125. }
  12126. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12127. var gl = _this._gl;
  12128. var isPot = (img.width === potWidth && img.height === potHeight);
  12129. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12130. if (isPot) {
  12131. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12132. return false;
  12133. }
  12134. // Using shaders to rescale because canvas.drawImage is lossy
  12135. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12136. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12137. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12139. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12140. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12142. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12143. _this._releaseTexture(source);
  12144. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12145. continuationCallback();
  12146. });
  12147. return true;
  12148. }, samplingMode);
  12149. };
  12150. if (!fromData || isBase64)
  12151. if (buffer instanceof HTMLImageElement) {
  12152. onload(buffer);
  12153. }
  12154. else {
  12155. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12156. }
  12157. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12158. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12159. else
  12160. onload(buffer);
  12161. }
  12162. return texture;
  12163. };
  12164. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12165. var _this = this;
  12166. var rtt = this.createRenderTargetTexture({
  12167. width: destination.width,
  12168. height: destination.height,
  12169. }, {
  12170. generateMipMaps: false,
  12171. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12172. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12173. generateDepthBuffer: false,
  12174. generateStencilBuffer: false
  12175. });
  12176. if (!this._rescalePostProcess) {
  12177. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12178. }
  12179. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12180. _this._rescalePostProcess.onApply = function (effect) {
  12181. effect._bindTexture("textureSampler", source);
  12182. };
  12183. var hostingScene = scene;
  12184. if (!hostingScene) {
  12185. hostingScene = _this.scenes[_this.scenes.length - 1];
  12186. }
  12187. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12188. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12189. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12190. _this.unBindFramebuffer(rtt);
  12191. _this._releaseTexture(rtt);
  12192. if (onComplete) {
  12193. onComplete();
  12194. }
  12195. });
  12196. };
  12197. Engine.prototype._getInternalFormat = function (format) {
  12198. var internalFormat = this._gl.RGBA;
  12199. switch (format) {
  12200. case Engine.TEXTUREFORMAT_ALPHA:
  12201. internalFormat = this._gl.ALPHA;
  12202. break;
  12203. case Engine.TEXTUREFORMAT_LUMINANCE:
  12204. internalFormat = this._gl.LUMINANCE;
  12205. break;
  12206. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12207. internalFormat = this._gl.LUMINANCE_ALPHA;
  12208. break;
  12209. case Engine.TEXTUREFORMAT_RGB:
  12210. internalFormat = this._gl.RGB;
  12211. break;
  12212. case Engine.TEXTUREFORMAT_RGBA:
  12213. internalFormat = this._gl.RGBA;
  12214. break;
  12215. }
  12216. return internalFormat;
  12217. };
  12218. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12219. if (compression === void 0) { compression = null; }
  12220. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12221. if (!texture) {
  12222. return;
  12223. }
  12224. var internalFormat = this._getInternalFormat(format);
  12225. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12226. var textureType = this._getWebGLTextureType(type);
  12227. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12228. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12229. if (!this._doNotHandleContextLost) {
  12230. texture._bufferView = data;
  12231. texture.format = format;
  12232. texture.type = type;
  12233. texture.invertY = invertY;
  12234. texture._compression = compression;
  12235. }
  12236. if (texture.width % 4 !== 0) {
  12237. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12238. }
  12239. if (compression && data) {
  12240. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12241. }
  12242. else {
  12243. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12244. }
  12245. if (texture.generateMipMaps) {
  12246. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12247. }
  12248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12249. // this.resetTextureCache();
  12250. texture.isReady = true;
  12251. };
  12252. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12253. if (compression === void 0) { compression = null; }
  12254. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12255. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12256. texture.baseWidth = width;
  12257. texture.baseHeight = height;
  12258. texture.width = width;
  12259. texture.height = height;
  12260. texture.format = format;
  12261. texture.generateMipMaps = generateMipMaps;
  12262. texture.samplingMode = samplingMode;
  12263. texture.invertY = invertY;
  12264. texture._compression = compression;
  12265. texture.type = type;
  12266. if (!this._doNotHandleContextLost) {
  12267. texture._bufferView = data;
  12268. }
  12269. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12270. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12271. // Filters
  12272. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12273. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12274. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12275. if (generateMipMaps) {
  12276. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12277. }
  12278. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12279. this._internalTexturesCache.push(texture);
  12280. return texture;
  12281. };
  12282. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12283. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12284. texture.baseWidth = width;
  12285. texture.baseHeight = height;
  12286. if (generateMipMaps) {
  12287. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12288. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12289. }
  12290. // this.resetTextureCache();
  12291. texture.width = width;
  12292. texture.height = height;
  12293. texture.isReady = false;
  12294. texture.generateMipMaps = generateMipMaps;
  12295. texture.samplingMode = samplingMode;
  12296. this.updateTextureSamplingMode(samplingMode, texture);
  12297. this._internalTexturesCache.push(texture);
  12298. return texture;
  12299. };
  12300. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12301. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12302. if (texture.isCube) {
  12303. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12304. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12305. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12306. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12307. }
  12308. else if (texture.is3D) {
  12309. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12310. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12311. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12312. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12313. }
  12314. else {
  12315. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12316. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12317. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12318. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12319. }
  12320. texture.samplingMode = samplingMode;
  12321. };
  12322. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12323. if (premulAlpha === void 0) { premulAlpha = false; }
  12324. if (!texture) {
  12325. return;
  12326. }
  12327. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12328. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12329. if (premulAlpha) {
  12330. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12331. }
  12332. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12333. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12334. if (texture.generateMipMaps) {
  12335. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12336. }
  12337. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12338. if (premulAlpha) {
  12339. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12340. }
  12341. texture.isReady = true;
  12342. };
  12343. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12344. if (!texture || texture._isDisabled) {
  12345. return;
  12346. }
  12347. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12348. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12349. try {
  12350. // Testing video texture support
  12351. if (this._videoTextureSupported === undefined) {
  12352. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12353. if (this._gl.getError() !== 0) {
  12354. this._videoTextureSupported = false;
  12355. }
  12356. else {
  12357. this._videoTextureSupported = true;
  12358. }
  12359. }
  12360. // Copy video through the current working canvas if video texture is not supported
  12361. if (!this._videoTextureSupported) {
  12362. if (!texture._workingCanvas) {
  12363. texture._workingCanvas = document.createElement("canvas");
  12364. var context = texture._workingCanvas.getContext("2d");
  12365. if (!context) {
  12366. throw new Error("Unable to get 2d context");
  12367. }
  12368. texture._workingContext = context;
  12369. texture._workingCanvas.width = texture.width;
  12370. texture._workingCanvas.height = texture.height;
  12371. }
  12372. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12373. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12374. }
  12375. else {
  12376. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12377. }
  12378. if (texture.generateMipMaps) {
  12379. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12380. }
  12381. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12382. // this.resetTextureCache();
  12383. texture.isReady = true;
  12384. }
  12385. catch (ex) {
  12386. // Something unexpected
  12387. // Let's disable the texture
  12388. texture._isDisabled = true;
  12389. }
  12390. };
  12391. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12392. var fullOptions = new RenderTargetCreationOptions();
  12393. if (options !== undefined && typeof options === "object") {
  12394. fullOptions.generateMipMaps = options.generateMipMaps;
  12395. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12396. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12397. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12398. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12399. }
  12400. else {
  12401. fullOptions.generateMipMaps = options;
  12402. fullOptions.generateDepthBuffer = true;
  12403. fullOptions.generateStencilBuffer = false;
  12404. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12405. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12406. }
  12407. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12408. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12409. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12410. }
  12411. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12412. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12413. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12414. }
  12415. var gl = this._gl;
  12416. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12417. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12418. var width = size.width || size;
  12419. var height = size.height || size;
  12420. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12421. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12422. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12423. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12424. }
  12425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12429. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12430. // Create the framebuffer
  12431. var framebuffer = gl.createFramebuffer();
  12432. this.bindUnboundFramebuffer(framebuffer);
  12433. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12434. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12435. if (fullOptions.generateMipMaps) {
  12436. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12437. }
  12438. // Unbind
  12439. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12440. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12441. this.bindUnboundFramebuffer(null);
  12442. texture._framebuffer = framebuffer;
  12443. texture.baseWidth = width;
  12444. texture.baseHeight = height;
  12445. texture.width = width;
  12446. texture.height = height;
  12447. texture.isReady = true;
  12448. texture.samples = 1;
  12449. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12450. texture.samplingMode = fullOptions.samplingMode;
  12451. texture.type = fullOptions.type;
  12452. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12453. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12454. // this.resetTextureCache();
  12455. this._internalTexturesCache.push(texture);
  12456. return texture;
  12457. };
  12458. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12459. var generateMipMaps = false;
  12460. var generateDepthBuffer = true;
  12461. var generateStencilBuffer = false;
  12462. var generateDepthTexture = false;
  12463. var textureCount = 1;
  12464. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12465. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12466. var types = [], samplingModes = [];
  12467. if (options !== undefined) {
  12468. generateMipMaps = options.generateMipMaps;
  12469. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12470. generateStencilBuffer = options.generateStencilBuffer;
  12471. generateDepthTexture = options.generateDepthTexture;
  12472. textureCount = options.textureCount || 1;
  12473. if (options.types) {
  12474. types = options.types;
  12475. }
  12476. if (options.samplingModes) {
  12477. samplingModes = options.samplingModes;
  12478. }
  12479. }
  12480. var gl = this._gl;
  12481. // Create the framebuffer
  12482. var framebuffer = gl.createFramebuffer();
  12483. this.bindUnboundFramebuffer(framebuffer);
  12484. var width = size.width || size;
  12485. var height = size.height || size;
  12486. var textures = [];
  12487. var attachments = [];
  12488. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12489. for (var i = 0; i < textureCount; i++) {
  12490. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12491. var type = types[i] || defaultType;
  12492. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12493. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12494. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12495. }
  12496. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12497. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12498. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12499. }
  12500. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12501. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12502. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12503. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12504. }
  12505. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12506. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12507. textures.push(texture);
  12508. attachments.push(attachment);
  12509. gl.activeTexture(gl["TEXTURE" + i]);
  12510. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12514. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12515. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12516. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12517. if (generateMipMaps) {
  12518. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12519. }
  12520. // Unbind
  12521. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12522. texture._framebuffer = framebuffer;
  12523. texture._depthStencilBuffer = depthStencilBuffer;
  12524. texture.baseWidth = width;
  12525. texture.baseHeight = height;
  12526. texture.width = width;
  12527. texture.height = height;
  12528. texture.isReady = true;
  12529. texture.samples = 1;
  12530. texture.generateMipMaps = generateMipMaps;
  12531. texture.samplingMode = samplingMode;
  12532. texture.type = type;
  12533. texture._generateDepthBuffer = generateDepthBuffer;
  12534. texture._generateStencilBuffer = generateStencilBuffer;
  12535. texture._attachments = attachments;
  12536. this._internalTexturesCache.push(texture);
  12537. }
  12538. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12539. // Depth texture
  12540. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12541. gl.activeTexture(gl.TEXTURE0);
  12542. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12547. 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);
  12548. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12549. depthTexture._framebuffer = framebuffer;
  12550. depthTexture.baseWidth = width;
  12551. depthTexture.baseHeight = height;
  12552. depthTexture.width = width;
  12553. depthTexture.height = height;
  12554. depthTexture.isReady = true;
  12555. depthTexture.samples = 1;
  12556. depthTexture.generateMipMaps = generateMipMaps;
  12557. depthTexture.samplingMode = gl.NEAREST;
  12558. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12559. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12560. textures.push(depthTexture);
  12561. this._internalTexturesCache.push(depthTexture);
  12562. }
  12563. gl.drawBuffers(attachments);
  12564. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12565. this.bindUnboundFramebuffer(null);
  12566. this.resetTextureCache();
  12567. return textures;
  12568. };
  12569. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12570. if (samples === void 0) { samples = 1; }
  12571. var depthStencilBuffer = null;
  12572. var gl = this._gl;
  12573. // Create the depth/stencil buffer
  12574. if (generateStencilBuffer) {
  12575. depthStencilBuffer = gl.createRenderbuffer();
  12576. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12577. if (samples > 1) {
  12578. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12579. }
  12580. else {
  12581. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12582. }
  12583. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12584. }
  12585. else if (generateDepthBuffer) {
  12586. depthStencilBuffer = gl.createRenderbuffer();
  12587. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12588. if (samples > 1) {
  12589. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12590. }
  12591. else {
  12592. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12593. }
  12594. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12595. }
  12596. return depthStencilBuffer;
  12597. };
  12598. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12599. if (this.webGLVersion < 2 || !texture) {
  12600. return 1;
  12601. }
  12602. if (texture.samples === samples) {
  12603. return samples;
  12604. }
  12605. var gl = this._gl;
  12606. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12607. // Dispose previous render buffers
  12608. if (texture._depthStencilBuffer) {
  12609. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12610. texture._depthStencilBuffer = null;
  12611. }
  12612. if (texture._MSAAFramebuffer) {
  12613. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12614. texture._MSAAFramebuffer = null;
  12615. }
  12616. if (texture._MSAARenderBuffer) {
  12617. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12618. texture._MSAARenderBuffer = null;
  12619. }
  12620. if (samples > 1) {
  12621. var framebuffer = gl.createFramebuffer();
  12622. if (!framebuffer) {
  12623. throw new Error("Unable to create multi sampled framebuffer");
  12624. }
  12625. texture._MSAAFramebuffer = framebuffer;
  12626. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12627. var colorRenderbuffer = gl.createRenderbuffer();
  12628. if (!colorRenderbuffer) {
  12629. throw new Error("Unable to create multi sampled framebuffer");
  12630. }
  12631. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12632. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12633. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12634. texture._MSAARenderBuffer = colorRenderbuffer;
  12635. }
  12636. else {
  12637. this.bindUnboundFramebuffer(texture._framebuffer);
  12638. }
  12639. texture.samples = samples;
  12640. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12641. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12642. this.bindUnboundFramebuffer(null);
  12643. return samples;
  12644. };
  12645. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12646. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12647. return 1;
  12648. }
  12649. if (textures[0].samples === samples) {
  12650. return samples;
  12651. }
  12652. var gl = this._gl;
  12653. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12654. // Dispose previous render buffers
  12655. if (textures[0]._depthStencilBuffer) {
  12656. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12657. textures[0]._depthStencilBuffer = null;
  12658. }
  12659. if (textures[0]._MSAAFramebuffer) {
  12660. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12661. textures[0]._MSAAFramebuffer = null;
  12662. }
  12663. for (var i = 0; i < textures.length; i++) {
  12664. if (textures[i]._MSAARenderBuffer) {
  12665. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12666. textures[i]._MSAARenderBuffer = null;
  12667. }
  12668. }
  12669. if (samples > 1) {
  12670. var framebuffer = gl.createFramebuffer();
  12671. if (!framebuffer) {
  12672. throw new Error("Unable to create multi sampled framebuffer");
  12673. }
  12674. this.bindUnboundFramebuffer(framebuffer);
  12675. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12676. var attachments = [];
  12677. for (var i = 0; i < textures.length; i++) {
  12678. var texture = textures[i];
  12679. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12680. var colorRenderbuffer = gl.createRenderbuffer();
  12681. if (!colorRenderbuffer) {
  12682. throw new Error("Unable to create multi sampled framebuffer");
  12683. }
  12684. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12685. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12686. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12687. texture._MSAAFramebuffer = framebuffer;
  12688. texture._MSAARenderBuffer = colorRenderbuffer;
  12689. texture.samples = samples;
  12690. texture._depthStencilBuffer = depthStencilBuffer;
  12691. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12692. attachments.push(attachment);
  12693. }
  12694. gl.drawBuffers(attachments);
  12695. }
  12696. else {
  12697. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12698. }
  12699. this.bindUnboundFramebuffer(null);
  12700. return samples;
  12701. };
  12702. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12703. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12704. };
  12705. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12706. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12707. };
  12708. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12709. var gl = this._gl;
  12710. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12711. var generateMipMaps = true;
  12712. var generateDepthBuffer = true;
  12713. var generateStencilBuffer = false;
  12714. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12715. if (options !== undefined) {
  12716. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12717. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12718. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12719. if (options.samplingMode !== undefined) {
  12720. samplingMode = options.samplingMode;
  12721. }
  12722. }
  12723. texture.isCube = true;
  12724. texture.generateMipMaps = generateMipMaps;
  12725. texture.samples = 1;
  12726. texture.samplingMode = samplingMode;
  12727. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12728. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12729. for (var face = 0; face < 6; face++) {
  12730. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12731. }
  12732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12736. // Create the framebuffer
  12737. var framebuffer = gl.createFramebuffer();
  12738. this.bindUnboundFramebuffer(framebuffer);
  12739. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12740. // Mipmaps
  12741. if (texture.generateMipMaps) {
  12742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12743. }
  12744. // Unbind
  12745. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12746. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12747. this.bindUnboundFramebuffer(null);
  12748. texture._framebuffer = framebuffer;
  12749. texture.width = size;
  12750. texture.height = size;
  12751. texture.isReady = true;
  12752. //this.resetTextureCache();
  12753. this._internalTexturesCache.push(texture);
  12754. return texture;
  12755. };
  12756. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12757. var _this = this;
  12758. if (onLoad === void 0) { onLoad = null; }
  12759. if (onError === void 0) { onError = null; }
  12760. if (forcedExtension === void 0) { forcedExtension = null; }
  12761. var callback = function (loadData) {
  12762. if (!loadData) {
  12763. if (onLoad) {
  12764. onLoad(null);
  12765. }
  12766. return;
  12767. }
  12768. var texture = loadData.texture;
  12769. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12770. texture._lodGenerationScale = scale;
  12771. texture._lodGenerationOffset = offset;
  12772. if (_this._caps.textureLOD) {
  12773. // Do not add extra process if texture lod is supported.
  12774. if (onLoad) {
  12775. onLoad(texture);
  12776. }
  12777. return;
  12778. }
  12779. var mipSlices = 3;
  12780. var gl = _this._gl;
  12781. var width = loadData.width;
  12782. if (!width) {
  12783. return;
  12784. }
  12785. var textures = [];
  12786. for (var i = 0; i < mipSlices; i++) {
  12787. //compute LOD from even spacing in smoothness (matching shader calculation)
  12788. var smoothness = i / (mipSlices - 1);
  12789. var roughness = 1 - smoothness;
  12790. var minLODIndex = offset; // roughness = 0
  12791. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12792. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12793. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12794. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12795. glTextureFromLod.isCube = true;
  12796. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12801. if (loadData.isDDS) {
  12802. var info = loadData.info;
  12803. var data = loadData.data;
  12804. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12805. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12806. }
  12807. else {
  12808. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12809. }
  12810. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12811. // Wrap in a base texture for easy binding.
  12812. var lodTexture = new BABYLON.BaseTexture(scene);
  12813. lodTexture.isCube = true;
  12814. lodTexture._texture = glTextureFromLod;
  12815. glTextureFromLod.isReady = true;
  12816. textures.push(lodTexture);
  12817. }
  12818. texture._lodTextureHigh = textures[2];
  12819. texture._lodTextureMid = textures[1];
  12820. texture._lodTextureLow = textures[0];
  12821. if (onLoad) {
  12822. onLoad(texture);
  12823. }
  12824. };
  12825. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12826. };
  12827. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12828. var _this = this;
  12829. if (onLoad === void 0) { onLoad = null; }
  12830. if (onError === void 0) { onError = null; }
  12831. if (forcedExtension === void 0) { forcedExtension = null; }
  12832. var gl = this._gl;
  12833. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12834. texture.isCube = true;
  12835. texture.url = rootUrl;
  12836. texture.generateMipMaps = !noMipmap;
  12837. if (!this._doNotHandleContextLost) {
  12838. texture._extension = forcedExtension;
  12839. texture._files = files;
  12840. }
  12841. var isKTX = false;
  12842. var isDDS = false;
  12843. var lastDot = rootUrl.lastIndexOf('.');
  12844. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12845. if (this._textureFormatInUse) {
  12846. extension = this._textureFormatInUse;
  12847. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12848. isKTX = true;
  12849. }
  12850. else {
  12851. isDDS = (extension === ".dds");
  12852. }
  12853. var onerror = function (request, exception) {
  12854. if (onError && request) {
  12855. onError(request.status + " " + request.statusText, exception);
  12856. }
  12857. };
  12858. if (isKTX) {
  12859. this._loadFile(rootUrl, function (data) {
  12860. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12861. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12862. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12863. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12864. ktx.uploadLevels(_this._gl, !noMipmap);
  12865. _this.setCubeMapTextureParams(gl, loadMipmap);
  12866. texture.width = ktx.pixelWidth;
  12867. texture.height = ktx.pixelHeight;
  12868. texture.isReady = true;
  12869. }, undefined, undefined, true, onerror);
  12870. }
  12871. else if (isDDS) {
  12872. if (files && files.length === 6) {
  12873. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12874. var info;
  12875. var loadMipmap = false;
  12876. var width = 0;
  12877. for (var index = 0; index < imgs.length; index++) {
  12878. var data = imgs[index];
  12879. info = BABYLON.DDSTools.GetDDSInfo(data);
  12880. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12881. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12882. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12883. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12884. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12885. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12886. }
  12887. texture.width = info.width;
  12888. texture.height = info.height;
  12889. texture.type = info.textureType;
  12890. width = info.width;
  12891. }
  12892. _this.setCubeMapTextureParams(gl, loadMipmap);
  12893. texture.isReady = true;
  12894. if (onLoad) {
  12895. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12896. }
  12897. }, files, onError);
  12898. }
  12899. else {
  12900. this._loadFile(rootUrl, function (data) {
  12901. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12902. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12904. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12905. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12906. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12908. }
  12909. _this.setCubeMapTextureParams(gl, loadMipmap);
  12910. texture.width = info.width;
  12911. texture.height = info.height;
  12912. texture.isReady = true;
  12913. texture.type = info.textureType;
  12914. if (onLoad) {
  12915. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12916. }
  12917. }, undefined, undefined, true, onerror);
  12918. }
  12919. }
  12920. else {
  12921. if (!files) {
  12922. throw new Error("Cannot load cubemap because files were not defined");
  12923. }
  12924. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12925. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12926. var height = width;
  12927. _this._prepareWorkingCanvas();
  12928. if (!_this._workingCanvas || !_this._workingContext) {
  12929. return;
  12930. }
  12931. _this._workingCanvas.width = width;
  12932. _this._workingCanvas.height = height;
  12933. var faces = [
  12934. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12935. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12936. ];
  12937. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12938. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12939. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12940. for (var index = 0; index < faces.length; index++) {
  12941. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12942. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12943. }
  12944. if (!noMipmap) {
  12945. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12946. }
  12947. _this.setCubeMapTextureParams(gl, !noMipmap);
  12948. texture.width = width;
  12949. texture.height = height;
  12950. texture.isReady = true;
  12951. if (format) {
  12952. texture.format = format;
  12953. }
  12954. texture.onLoadedObservable.notifyObservers(texture);
  12955. texture.onLoadedObservable.clear();
  12956. if (onLoad) {
  12957. onLoad();
  12958. }
  12959. }, files, onError);
  12960. }
  12961. this._internalTexturesCache.push(texture);
  12962. return texture;
  12963. };
  12964. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12968. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12969. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12970. // this.resetTextureCache();
  12971. };
  12972. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12973. if (compression === void 0) { compression = null; }
  12974. if (level === void 0) { level = 0; }
  12975. texture._bufferViewArray = data;
  12976. texture.format = format;
  12977. texture.type = type;
  12978. texture.invertY = invertY;
  12979. texture._compression = compression;
  12980. var gl = this._gl;
  12981. var textureType = this._getWebGLTextureType(type);
  12982. var internalFormat = this._getInternalFormat(format);
  12983. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12984. var needConversion = false;
  12985. if (internalFormat === gl.RGB) {
  12986. internalFormat = gl.RGBA;
  12987. needConversion = true;
  12988. }
  12989. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12990. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12991. if (texture.width % 4 !== 0) {
  12992. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12993. }
  12994. // Data are known to be in +X +Y +Z -X -Y -Z
  12995. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12996. var faceData = data[faceIndex];
  12997. if (compression) {
  12998. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12999. }
  13000. else {
  13001. if (needConversion) {
  13002. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13003. }
  13004. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13005. }
  13006. }
  13007. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13008. if (isPot && texture.generateMipMaps && level === 0) {
  13009. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13010. }
  13011. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13012. // this.resetTextureCache();
  13013. texture.isReady = true;
  13014. };
  13015. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13016. if (compression === void 0) { compression = null; }
  13017. var gl = this._gl;
  13018. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13019. texture.isCube = true;
  13020. texture.generateMipMaps = generateMipMaps;
  13021. texture.format = format;
  13022. texture.type = type;
  13023. if (!this._doNotHandleContextLost) {
  13024. texture._bufferViewArray = data;
  13025. }
  13026. var textureType = this._getWebGLTextureType(type);
  13027. var internalFormat = this._getInternalFormat(format);
  13028. if (internalFormat === gl.RGB) {
  13029. internalFormat = gl.RGBA;
  13030. }
  13031. var width = size;
  13032. var height = width;
  13033. texture.width = width;
  13034. texture.height = height;
  13035. // Double check on POT to generate Mips.
  13036. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13037. if (!isPot) {
  13038. generateMipMaps = false;
  13039. }
  13040. // Upload data if needed. The texture won't be ready until then.
  13041. if (data) {
  13042. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13043. }
  13044. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13045. // Filters
  13046. if (data && generateMipMaps) {
  13047. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13048. }
  13049. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13051. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13052. }
  13053. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13056. }
  13057. else {
  13058. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13061. }
  13062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13064. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13065. return texture;
  13066. };
  13067. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13068. var _this = this;
  13069. if (onLoad === void 0) { onLoad = null; }
  13070. if (onError === void 0) { onError = null; }
  13071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13072. if (invertY === void 0) { invertY = false; }
  13073. var gl = this._gl;
  13074. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13075. scene._addPendingData(texture);
  13076. texture.url = url;
  13077. this._internalTexturesCache.push(texture);
  13078. var onerror = function (request, exception) {
  13079. scene._removePendingData(texture);
  13080. if (onError && request) {
  13081. onError(request.status + " " + request.statusText, exception);
  13082. }
  13083. };
  13084. var internalCallback = function (data) {
  13085. var width = texture.width;
  13086. var faceDataArrays = callback(data);
  13087. if (!faceDataArrays) {
  13088. return;
  13089. }
  13090. if (mipmmapGenerator) {
  13091. var textureType = _this._getWebGLTextureType(type);
  13092. var internalFormat = _this._getInternalFormat(format);
  13093. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13094. var needConversion = false;
  13095. if (internalFormat === gl.RGB) {
  13096. internalFormat = gl.RGBA;
  13097. needConversion = true;
  13098. }
  13099. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13100. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13101. var mipData = mipmmapGenerator(faceDataArrays);
  13102. for (var level = 0; level < mipData.length; level++) {
  13103. var mipSize = width >> level;
  13104. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13105. var mipFaceData = mipData[level][faceIndex];
  13106. if (needConversion) {
  13107. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13108. }
  13109. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13110. }
  13111. }
  13112. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13113. }
  13114. else {
  13115. texture.generateMipMaps = !noMipmap;
  13116. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13117. }
  13118. texture.isReady = true;
  13119. // this.resetTextureCache();
  13120. scene._removePendingData(texture);
  13121. if (onLoad) {
  13122. onLoad();
  13123. }
  13124. };
  13125. this._loadFile(url, function (data) {
  13126. internalCallback(data);
  13127. }, undefined, scene.database, true, onerror);
  13128. return texture;
  13129. };
  13130. ;
  13131. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13132. if (compression === void 0) { compression = null; }
  13133. var internalFormat = this._getInternalFormat(format);
  13134. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13135. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13136. if (!this._doNotHandleContextLost) {
  13137. texture._bufferView = data;
  13138. texture.format = format;
  13139. texture.invertY = invertY;
  13140. texture._compression = compression;
  13141. }
  13142. if (texture.width % 4 !== 0) {
  13143. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13144. }
  13145. if (compression && data) {
  13146. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13147. }
  13148. else {
  13149. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13150. }
  13151. if (texture.generateMipMaps) {
  13152. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13153. }
  13154. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13155. // this.resetTextureCache();
  13156. texture.isReady = true;
  13157. };
  13158. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13159. if (compression === void 0) { compression = null; }
  13160. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13161. texture.baseWidth = width;
  13162. texture.baseHeight = height;
  13163. texture.baseDepth = depth;
  13164. texture.width = width;
  13165. texture.height = height;
  13166. texture.depth = depth;
  13167. texture.format = format;
  13168. texture.generateMipMaps = generateMipMaps;
  13169. texture.samplingMode = samplingMode;
  13170. texture.is3D = true;
  13171. if (!this._doNotHandleContextLost) {
  13172. texture._bufferView = data;
  13173. }
  13174. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13175. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13176. // Filters
  13177. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13179. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13180. if (generateMipMaps) {
  13181. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13182. }
  13183. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13184. this._internalTexturesCache.push(texture);
  13185. return texture;
  13186. };
  13187. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13188. var gl = this._gl;
  13189. if (!gl) {
  13190. return;
  13191. }
  13192. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13195. if (!noMipmap && !isCompressed) {
  13196. gl.generateMipmap(gl.TEXTURE_2D);
  13197. }
  13198. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13199. // this.resetTextureCache();
  13200. if (scene) {
  13201. scene._removePendingData(texture);
  13202. }
  13203. texture.onLoadedObservable.notifyObservers(texture);
  13204. texture.onLoadedObservable.clear();
  13205. };
  13206. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13207. var _this = this;
  13208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13209. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13210. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13211. var gl = this._gl;
  13212. if (!gl) {
  13213. return;
  13214. }
  13215. if (!texture._webGLTexture) {
  13216. // this.resetTextureCache();
  13217. if (scene) {
  13218. scene._removePendingData(texture);
  13219. }
  13220. return;
  13221. }
  13222. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13223. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13224. texture.baseWidth = width;
  13225. texture.baseHeight = height;
  13226. texture.width = potWidth;
  13227. texture.height = potHeight;
  13228. texture.isReady = true;
  13229. if (processFunction(potWidth, potHeight, function () {
  13230. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13231. })) {
  13232. // Returning as texture needs extra async steps
  13233. return;
  13234. }
  13235. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13236. };
  13237. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13238. // Create new RGBA data container.
  13239. var rgbaData;
  13240. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13241. rgbaData = new Float32Array(width * height * 4);
  13242. }
  13243. else {
  13244. rgbaData = new Uint32Array(width * height * 4);
  13245. }
  13246. // Convert each pixel.
  13247. for (var x = 0; x < width; x++) {
  13248. for (var y = 0; y < height; y++) {
  13249. var index = (y * width + x) * 3;
  13250. var newIndex = (y * width + x) * 4;
  13251. // Map Old Value to new value.
  13252. rgbaData[newIndex + 0] = rgbData[index + 0];
  13253. rgbaData[newIndex + 1] = rgbData[index + 1];
  13254. rgbaData[newIndex + 2] = rgbData[index + 2];
  13255. // Add fully opaque alpha channel.
  13256. rgbaData[newIndex + 3] = 1;
  13257. }
  13258. }
  13259. return rgbaData;
  13260. };
  13261. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13262. var gl = this._gl;
  13263. if (texture._framebuffer) {
  13264. gl.deleteFramebuffer(texture._framebuffer);
  13265. texture._framebuffer = null;
  13266. }
  13267. if (texture._depthStencilBuffer) {
  13268. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13269. texture._depthStencilBuffer = null;
  13270. }
  13271. if (texture._MSAAFramebuffer) {
  13272. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13273. texture._MSAAFramebuffer = null;
  13274. }
  13275. if (texture._MSAARenderBuffer) {
  13276. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13277. texture._MSAARenderBuffer = null;
  13278. }
  13279. };
  13280. Engine.prototype._releaseTexture = function (texture) {
  13281. var gl = this._gl;
  13282. this._releaseFramebufferObjects(texture);
  13283. gl.deleteTexture(texture._webGLTexture);
  13284. // Unbind channels
  13285. this.unbindAllTextures();
  13286. var index = this._internalTexturesCache.indexOf(texture);
  13287. if (index !== -1) {
  13288. this._internalTexturesCache.splice(index, 1);
  13289. }
  13290. // Integrated fixed lod samplers.
  13291. if (texture._lodTextureHigh) {
  13292. texture._lodTextureHigh.dispose();
  13293. }
  13294. if (texture._lodTextureMid) {
  13295. texture._lodTextureMid.dispose();
  13296. }
  13297. if (texture._lodTextureLow) {
  13298. texture._lodTextureLow.dispose();
  13299. }
  13300. };
  13301. Engine.prototype.setProgram = function (program) {
  13302. if (this._currentProgram !== program) {
  13303. this._gl.useProgram(program);
  13304. this._currentProgram = program;
  13305. }
  13306. };
  13307. Engine.prototype.bindSamplers = function (effect) {
  13308. this.setProgram(effect.getProgram());
  13309. var samplers = effect.getSamplers();
  13310. for (var index = 0; index < samplers.length; index++) {
  13311. var uniform = effect.getUniform(samplers[index]);
  13312. if (uniform) {
  13313. this._boundUniforms[index] = uniform;
  13314. }
  13315. }
  13316. this._currentEffect = null;
  13317. };
  13318. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13319. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13320. return;
  13321. }
  13322. // Remove
  13323. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13324. // Bind last to it
  13325. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13326. // Bind to dummy
  13327. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13328. };
  13329. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13330. if (!internalTexture) {
  13331. return -1;
  13332. }
  13333. internalTexture._initialSlot = channel;
  13334. if (this.disableTextureBindingOptimization) {
  13335. if (channel !== internalTexture._designatedSlot) {
  13336. this._textureCollisions.addCount(1, false);
  13337. }
  13338. }
  13339. else {
  13340. if (channel !== internalTexture._designatedSlot) {
  13341. if (internalTexture._designatedSlot > -1) {
  13342. return internalTexture._designatedSlot;
  13343. }
  13344. else {
  13345. // No slot for this texture, let's pick a new one (if we find a free slot)
  13346. if (this._nextFreeTextureSlots.length) {
  13347. return this._nextFreeTextureSlots[0];
  13348. }
  13349. // We need to recycle the oldest bound texture, sorry.
  13350. this._textureCollisions.addCount(1, false);
  13351. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13352. }
  13353. }
  13354. }
  13355. return channel;
  13356. };
  13357. Engine.prototype._linkTrackers = function (previous, next) {
  13358. previous.next = next;
  13359. next.previous = previous;
  13360. };
  13361. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13362. var currentSlot = internalTexture._designatedSlot;
  13363. if (currentSlot === -1) {
  13364. return -1;
  13365. }
  13366. internalTexture._designatedSlot = -1;
  13367. if (this.disableTextureBindingOptimization) {
  13368. return -1;
  13369. }
  13370. // Remove from bound list
  13371. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13372. // Free the slot
  13373. this._boundTexturesCache[currentSlot] = null;
  13374. this._nextFreeTextureSlots.push(currentSlot);
  13375. return currentSlot;
  13376. };
  13377. Engine.prototype._activateCurrentTexture = function () {
  13378. if (this._currentTextureChannel !== this._activeChannel) {
  13379. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13380. this._currentTextureChannel = this._activeChannel;
  13381. }
  13382. };
  13383. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13384. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13385. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13386. this._activeChannel = texture._designatedSlot;
  13387. }
  13388. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13389. var isTextureForRendering = texture && texture._initialSlot > -1;
  13390. if (currentTextureBound !== texture) {
  13391. if (currentTextureBound) {
  13392. this._removeDesignatedSlot(currentTextureBound);
  13393. }
  13394. this._activateCurrentTexture();
  13395. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13396. this._boundTexturesCache[this._activeChannel] = texture;
  13397. if (texture) {
  13398. if (!this.disableTextureBindingOptimization) {
  13399. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13400. if (slotIndex > -1) {
  13401. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13402. }
  13403. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13404. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13405. }
  13406. texture._designatedSlot = this._activeChannel;
  13407. }
  13408. }
  13409. else if (forTextureDataUpdate) {
  13410. this._activateCurrentTexture();
  13411. }
  13412. if (isTextureForRendering && !forTextureDataUpdate) {
  13413. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13414. }
  13415. };
  13416. Engine.prototype._bindTexture = function (channel, texture) {
  13417. if (channel < 0) {
  13418. return;
  13419. }
  13420. if (texture) {
  13421. channel = this._getCorrectTextureChannel(channel, texture);
  13422. }
  13423. this._activeChannel = channel;
  13424. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13425. };
  13426. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13427. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13428. };
  13429. Engine.prototype.unbindAllTextures = function () {
  13430. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13431. this._activeChannel = channel;
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13433. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13434. if (this.webGLVersion > 1) {
  13435. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13436. }
  13437. }
  13438. };
  13439. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13440. if (channel < 0) {
  13441. return;
  13442. }
  13443. if (uniform) {
  13444. this._boundUniforms[channel] = uniform;
  13445. }
  13446. this._setTexture(channel, texture);
  13447. };
  13448. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13449. var uniform = this._boundUniforms[sourceSlot];
  13450. if (uniform._currentState === destination) {
  13451. return;
  13452. }
  13453. this._gl.uniform1i(uniform, destination);
  13454. uniform._currentState = destination;
  13455. };
  13456. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13457. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13458. // Not ready?
  13459. if (!texture) {
  13460. if (this._boundTexturesCache[channel] != null) {
  13461. this._activeChannel = channel;
  13462. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13463. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13464. if (this.webGLVersion > 1) {
  13465. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13466. }
  13467. }
  13468. return false;
  13469. }
  13470. // Video
  13471. if (texture.video) {
  13472. this._activeChannel = channel;
  13473. texture.update();
  13474. }
  13475. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13476. texture.delayLoad();
  13477. return false;
  13478. }
  13479. var internalTexture;
  13480. if (texture.isReady()) {
  13481. internalTexture = texture.getInternalTexture();
  13482. }
  13483. else if (texture.isCube) {
  13484. internalTexture = this.emptyCubeTexture;
  13485. }
  13486. else if (texture.is3D) {
  13487. internalTexture = this.emptyTexture3D;
  13488. }
  13489. else {
  13490. internalTexture = this.emptyTexture;
  13491. }
  13492. if (!isPartOfTextureArray) {
  13493. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13494. }
  13495. if (this._boundTexturesCache[channel] === internalTexture) {
  13496. this._moveBoundTextureOnTop(internalTexture);
  13497. if (!isPartOfTextureArray) {
  13498. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13499. }
  13500. return false;
  13501. }
  13502. this._activeChannel = channel;
  13503. if (internalTexture && internalTexture.is3D) {
  13504. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13505. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13506. internalTexture._cachedWrapU = texture.wrapU;
  13507. switch (texture.wrapU) {
  13508. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13509. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13510. break;
  13511. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13512. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13513. break;
  13514. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13515. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13516. break;
  13517. }
  13518. }
  13519. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13520. internalTexture._cachedWrapV = texture.wrapV;
  13521. switch (texture.wrapV) {
  13522. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13523. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13524. break;
  13525. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13526. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13527. break;
  13528. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13530. break;
  13531. }
  13532. }
  13533. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13534. internalTexture._cachedWrapR = texture.wrapR;
  13535. switch (texture.wrapV) {
  13536. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13537. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13538. break;
  13539. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13540. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13541. break;
  13542. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13543. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13544. break;
  13545. }
  13546. }
  13547. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13548. }
  13549. else if (internalTexture && internalTexture.isCube) {
  13550. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13551. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13552. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13553. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13554. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13555. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13556. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13557. }
  13558. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13559. }
  13560. else {
  13561. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13562. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13563. internalTexture._cachedWrapU = texture.wrapU;
  13564. switch (texture.wrapU) {
  13565. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13566. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13567. break;
  13568. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13569. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13570. break;
  13571. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13572. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13573. break;
  13574. }
  13575. }
  13576. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13577. internalTexture._cachedWrapV = texture.wrapV;
  13578. switch (texture.wrapV) {
  13579. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13580. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13581. break;
  13582. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13584. break;
  13585. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13587. break;
  13588. }
  13589. }
  13590. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13591. }
  13592. return true;
  13593. };
  13594. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13595. if (channel < 0 || !uniform) {
  13596. return;
  13597. }
  13598. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13599. this._textureUnits = new Int32Array(textures.length);
  13600. }
  13601. for (var i = 0; i < textures.length; i++) {
  13602. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13603. }
  13604. this._gl.uniform1iv(uniform, this._textureUnits);
  13605. for (var index = 0; index < textures.length; index++) {
  13606. this._setTexture(this._textureUnits[index], textures[index], true);
  13607. }
  13608. };
  13609. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13610. var internalTexture = texture.getInternalTexture();
  13611. if (!internalTexture) {
  13612. return;
  13613. }
  13614. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13615. var value = texture.anisotropicFilteringLevel;
  13616. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13617. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13618. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13619. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13620. }
  13621. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13622. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13623. internalTexture._cachedAnisotropicFilteringLevel = value;
  13624. }
  13625. };
  13626. Engine.prototype.readPixels = function (x, y, width, height) {
  13627. var data = new Uint8Array(height * width * 4);
  13628. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13629. return data;
  13630. };
  13631. /**
  13632. * Add an externaly attached data from its key.
  13633. * This method call will fail and return false, if such key already exists.
  13634. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13635. * @param key the unique key that identifies the data
  13636. * @param data the data object to associate to the key for this Engine instance
  13637. * @return true if no such key were already present and the data was added successfully, false otherwise
  13638. */
  13639. Engine.prototype.addExternalData = function (key, data) {
  13640. if (!this._externalData) {
  13641. this._externalData = new BABYLON.StringDictionary();
  13642. }
  13643. return this._externalData.add(key, data);
  13644. };
  13645. /**
  13646. * Get an externaly attached data from its key
  13647. * @param key the unique key that identifies the data
  13648. * @return the associated data, if present (can be null), or undefined if not present
  13649. */
  13650. Engine.prototype.getExternalData = function (key) {
  13651. if (!this._externalData) {
  13652. this._externalData = new BABYLON.StringDictionary();
  13653. }
  13654. return this._externalData.get(key);
  13655. };
  13656. /**
  13657. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13658. * @param key the unique key that identifies the data
  13659. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13660. * @return the associated data, can be null if the factory returned null.
  13661. */
  13662. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13663. if (!this._externalData) {
  13664. this._externalData = new BABYLON.StringDictionary();
  13665. }
  13666. return this._externalData.getOrAddWithFactory(key, factory);
  13667. };
  13668. /**
  13669. * Remove an externaly attached data from the Engine instance
  13670. * @param key the unique key that identifies the data
  13671. * @return true if the data was successfully removed, false if it doesn't exist
  13672. */
  13673. Engine.prototype.removeExternalData = function (key) {
  13674. if (!this._externalData) {
  13675. this._externalData = new BABYLON.StringDictionary();
  13676. }
  13677. return this._externalData.remove(key);
  13678. };
  13679. Engine.prototype.unbindAllAttributes = function () {
  13680. if (this._mustWipeVertexAttributes) {
  13681. this._mustWipeVertexAttributes = false;
  13682. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13683. this._gl.disableVertexAttribArray(i);
  13684. this._vertexAttribArraysEnabled[i] = false;
  13685. this._currentBufferPointers[i].active = false;
  13686. }
  13687. return;
  13688. }
  13689. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13690. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13691. continue;
  13692. }
  13693. this._gl.disableVertexAttribArray(i);
  13694. this._vertexAttribArraysEnabled[i] = false;
  13695. this._currentBufferPointers[i].active = false;
  13696. }
  13697. };
  13698. Engine.prototype.releaseEffects = function () {
  13699. for (var name in this._compiledEffects) {
  13700. this._deleteProgram(this._compiledEffects[name]._program);
  13701. }
  13702. this._compiledEffects = {};
  13703. };
  13704. // Dispose
  13705. Engine.prototype.dispose = function () {
  13706. this.hideLoadingUI();
  13707. this.stopRenderLoop();
  13708. // Release postProcesses
  13709. while (this.postProcesses.length) {
  13710. this.postProcesses[0].dispose();
  13711. }
  13712. // Empty texture
  13713. if (this._emptyTexture) {
  13714. this._releaseTexture(this._emptyTexture);
  13715. this._emptyTexture = null;
  13716. }
  13717. if (this._emptyCubeTexture) {
  13718. this._releaseTexture(this._emptyCubeTexture);
  13719. this._emptyCubeTexture = null;
  13720. }
  13721. // Rescale PP
  13722. if (this._rescalePostProcess) {
  13723. this._rescalePostProcess.dispose();
  13724. }
  13725. // Release scenes
  13726. while (this.scenes.length) {
  13727. this.scenes[0].dispose();
  13728. }
  13729. // Release audio engine
  13730. if (Engine.audioEngine) {
  13731. Engine.audioEngine.dispose();
  13732. }
  13733. // Release effects
  13734. this.releaseEffects();
  13735. // Unbind
  13736. this.unbindAllAttributes();
  13737. if (this._dummyFramebuffer) {
  13738. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13739. }
  13740. //WebVR
  13741. this.disableVR();
  13742. // Events
  13743. if (BABYLON.Tools.IsWindowObjectExist()) {
  13744. window.removeEventListener("blur", this._onBlur);
  13745. window.removeEventListener("focus", this._onFocus);
  13746. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13747. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13748. if (this._renderingCanvas) {
  13749. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13750. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13751. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13752. if (!this._doNotHandleContextLost) {
  13753. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13754. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13755. }
  13756. }
  13757. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13758. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13759. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13760. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13761. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13762. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13763. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13764. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13765. if (this._onVrDisplayConnect) {
  13766. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13767. if (this._onVrDisplayDisconnect) {
  13768. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13769. }
  13770. if (this._onVrDisplayPresentChange) {
  13771. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13772. }
  13773. this._onVrDisplayConnect = null;
  13774. this._onVrDisplayDisconnect = null;
  13775. }
  13776. }
  13777. // Remove from Instances
  13778. var index = Engine.Instances.indexOf(this);
  13779. if (index >= 0) {
  13780. Engine.Instances.splice(index, 1);
  13781. }
  13782. this._workingCanvas = null;
  13783. this._workingContext = null;
  13784. this._currentBufferPointers = [];
  13785. this._renderingCanvas = null;
  13786. this._currentProgram = null;
  13787. this.onResizeObservable.clear();
  13788. this.onCanvasBlurObservable.clear();
  13789. this.onCanvasFocusObservable.clear();
  13790. this.onCanvasPointerOutObservable.clear();
  13791. this.onBeginFrameObservable.clear();
  13792. this.onEndFrameObservable.clear();
  13793. BABYLON.Effect.ResetCache();
  13794. // Abort active requests
  13795. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13796. var request = _a[_i];
  13797. request.abort();
  13798. }
  13799. };
  13800. // Loading screen
  13801. Engine.prototype.displayLoadingUI = function () {
  13802. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13803. return;
  13804. }
  13805. var loadingScreen = this.loadingScreen;
  13806. if (loadingScreen) {
  13807. loadingScreen.displayLoadingUI();
  13808. }
  13809. };
  13810. Engine.prototype.hideLoadingUI = function () {
  13811. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13812. return;
  13813. }
  13814. var loadingScreen = this.loadingScreen;
  13815. if (loadingScreen) {
  13816. loadingScreen.hideLoadingUI();
  13817. }
  13818. };
  13819. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13820. get: function () {
  13821. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13822. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13823. return this._loadingScreen;
  13824. },
  13825. set: function (loadingScreen) {
  13826. this._loadingScreen = loadingScreen;
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13832. set: function (text) {
  13833. this.loadingScreen.loadingUIText = text;
  13834. },
  13835. enumerable: true,
  13836. configurable: true
  13837. });
  13838. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13839. set: function (color) {
  13840. this.loadingScreen.loadingUIBackgroundColor = color;
  13841. },
  13842. enumerable: true,
  13843. configurable: true
  13844. });
  13845. Engine.prototype.attachContextLostEvent = function (callback) {
  13846. if (this._renderingCanvas) {
  13847. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13848. }
  13849. };
  13850. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13851. if (this._renderingCanvas) {
  13852. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13853. }
  13854. };
  13855. Engine.prototype.getVertexShaderSource = function (program) {
  13856. var shaders = this._gl.getAttachedShaders(program);
  13857. if (!shaders) {
  13858. return null;
  13859. }
  13860. return this._gl.getShaderSource(shaders[0]);
  13861. };
  13862. Engine.prototype.getFragmentShaderSource = function (program) {
  13863. var shaders = this._gl.getAttachedShaders(program);
  13864. if (!shaders) {
  13865. return null;
  13866. }
  13867. return this._gl.getShaderSource(shaders[1]);
  13868. };
  13869. Engine.prototype.getError = function () {
  13870. return this._gl.getError();
  13871. };
  13872. // FPS
  13873. Engine.prototype.getFps = function () {
  13874. return this._fps;
  13875. };
  13876. Engine.prototype.getDeltaTime = function () {
  13877. return this._deltaTime;
  13878. };
  13879. Engine.prototype._measureFps = function () {
  13880. this._performanceMonitor.sampleFrame();
  13881. this._fps = this._performanceMonitor.averageFPS;
  13882. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13883. };
  13884. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13885. if (faceIndex === void 0) { faceIndex = -1; }
  13886. var gl = this._gl;
  13887. if (!this._dummyFramebuffer) {
  13888. var dummy = gl.createFramebuffer();
  13889. if (!dummy) {
  13890. throw new Error("Unable to create dummy framebuffer");
  13891. }
  13892. this._dummyFramebuffer = dummy;
  13893. }
  13894. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13895. if (faceIndex > -1) {
  13896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13897. }
  13898. else {
  13899. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13900. }
  13901. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13902. var buffer;
  13903. switch (readType) {
  13904. case gl.UNSIGNED_BYTE:
  13905. buffer = new Uint8Array(4 * width * height);
  13906. readType = gl.UNSIGNED_BYTE;
  13907. break;
  13908. default:
  13909. buffer = new Float32Array(4 * width * height);
  13910. readType = gl.FLOAT;
  13911. break;
  13912. }
  13913. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13914. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13915. return buffer;
  13916. };
  13917. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13918. if (this._webGLVersion > 1) {
  13919. return this._caps.colorBufferFloat;
  13920. }
  13921. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13922. };
  13923. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13924. if (this._webGLVersion > 1) {
  13925. return this._caps.colorBufferFloat;
  13926. }
  13927. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13928. };
  13929. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13930. Engine.prototype._canRenderToFramebuffer = function (type) {
  13931. var gl = this._gl;
  13932. //clear existing errors
  13933. while (gl.getError() !== gl.NO_ERROR) { }
  13934. var successful = true;
  13935. var texture = gl.createTexture();
  13936. gl.bindTexture(gl.TEXTURE_2D, texture);
  13937. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13939. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13940. var fb = gl.createFramebuffer();
  13941. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13942. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13943. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13944. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13945. successful = successful && (gl.getError() === gl.NO_ERROR);
  13946. //try render by clearing frame buffer's color buffer
  13947. if (successful) {
  13948. gl.clear(gl.COLOR_BUFFER_BIT);
  13949. successful = successful && (gl.getError() === gl.NO_ERROR);
  13950. }
  13951. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13952. if (successful) {
  13953. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13954. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13955. var readFormat = gl.RGBA;
  13956. var readType = gl.UNSIGNED_BYTE;
  13957. var buffer = new Uint8Array(4);
  13958. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13959. successful = successful && (gl.getError() === gl.NO_ERROR);
  13960. }
  13961. //clean up
  13962. gl.deleteTexture(texture);
  13963. gl.deleteFramebuffer(fb);
  13964. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13965. //clear accumulated errors
  13966. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13967. return successful;
  13968. };
  13969. Engine.prototype._getWebGLTextureType = function (type) {
  13970. if (type === Engine.TEXTURETYPE_FLOAT) {
  13971. return this._gl.FLOAT;
  13972. }
  13973. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13974. // Add Half Float Constant.
  13975. return this._gl.HALF_FLOAT_OES;
  13976. }
  13977. return this._gl.UNSIGNED_BYTE;
  13978. };
  13979. ;
  13980. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13981. if (this._webGLVersion === 1) {
  13982. return this._gl.RGBA;
  13983. }
  13984. if (type === Engine.TEXTURETYPE_FLOAT) {
  13985. return this._gl.RGBA32F;
  13986. }
  13987. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13988. return this._gl.RGBA16F;
  13989. }
  13990. return this._gl.RGBA;
  13991. };
  13992. ;
  13993. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13994. if (type === Engine.TEXTURETYPE_FLOAT) {
  13995. return this._gl.RGBA32F;
  13996. }
  13997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13998. return this._gl.RGBA16F;
  13999. }
  14000. return this._gl.RGBA8;
  14001. };
  14002. ;
  14003. Engine.prototype.createQuery = function () {
  14004. return this._gl.createQuery();
  14005. };
  14006. Engine.prototype.deleteQuery = function (query) {
  14007. this._gl.deleteQuery(query);
  14008. return this;
  14009. };
  14010. Engine.prototype.isQueryResultAvailable = function (query) {
  14011. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14012. };
  14013. Engine.prototype.getQueryResult = function (query) {
  14014. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14015. };
  14016. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14017. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14018. this._gl.beginQuery(glAlgorithm, query);
  14019. return this;
  14020. };
  14021. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14022. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14023. this._gl.endQuery(glAlgorithm);
  14024. return this;
  14025. };
  14026. /* Time queries */
  14027. Engine.prototype._createTimeQuery = function () {
  14028. var timerQuery = this._caps.timerQuery;
  14029. if (timerQuery.createQueryEXT) {
  14030. return timerQuery.createQueryEXT();
  14031. }
  14032. return this.createQuery();
  14033. };
  14034. Engine.prototype._deleteTimeQuery = function (query) {
  14035. var timerQuery = this._caps.timerQuery;
  14036. if (timerQuery.deleteQueryEXT) {
  14037. timerQuery.deleteQueryEXT(query);
  14038. return;
  14039. }
  14040. this.deleteQuery(query);
  14041. };
  14042. Engine.prototype._getTimeQueryResult = function (query) {
  14043. var timerQuery = this._caps.timerQuery;
  14044. if (timerQuery.getQueryObjectEXT) {
  14045. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14046. }
  14047. return this.getQueryResult(query);
  14048. };
  14049. Engine.prototype._getTimeQueryAvailability = function (query) {
  14050. var timerQuery = this._caps.timerQuery;
  14051. if (timerQuery.getQueryObjectEXT) {
  14052. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14053. }
  14054. return this.isQueryResultAvailable(query);
  14055. };
  14056. Engine.prototype.startTimeQuery = function () {
  14057. var timerQuery = this._caps.timerQuery;
  14058. if (!timerQuery) {
  14059. return null;
  14060. }
  14061. var token = new BABYLON._TimeToken();
  14062. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14063. if (this._caps.canUseTimestampForTimerQuery) {
  14064. token._startTimeQuery = this._createTimeQuery();
  14065. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14066. }
  14067. else {
  14068. if (this._currentNonTimestampToken) {
  14069. return this._currentNonTimestampToken;
  14070. }
  14071. token._timeElapsedQuery = this._createTimeQuery();
  14072. if (timerQuery.beginQueryEXT) {
  14073. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14074. }
  14075. else {
  14076. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14077. }
  14078. this._currentNonTimestampToken = token;
  14079. }
  14080. return token;
  14081. };
  14082. Engine.prototype.endTimeQuery = function (token) {
  14083. var timerQuery = this._caps.timerQuery;
  14084. if (!timerQuery || !token) {
  14085. return -1;
  14086. }
  14087. if (this._caps.canUseTimestampForTimerQuery) {
  14088. if (!token._startTimeQuery) {
  14089. return -1;
  14090. }
  14091. if (!token._endTimeQuery) {
  14092. token._endTimeQuery = this._createTimeQuery();
  14093. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14094. }
  14095. }
  14096. else if (!token._timeElapsedQueryEnded) {
  14097. if (!token._timeElapsedQuery) {
  14098. return -1;
  14099. }
  14100. if (timerQuery.endQueryEXT) {
  14101. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14102. }
  14103. else {
  14104. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14105. }
  14106. token._timeElapsedQueryEnded = true;
  14107. }
  14108. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14109. var available = false;
  14110. if (token._endTimeQuery) {
  14111. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14112. }
  14113. else if (token._timeElapsedQuery) {
  14114. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14115. }
  14116. if (available && !disjoint) {
  14117. var result = 0;
  14118. if (this._caps.canUseTimestampForTimerQuery) {
  14119. if (!token._startTimeQuery || !token._endTimeQuery) {
  14120. return -1;
  14121. }
  14122. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14123. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14124. result = timeEnd - timeStart;
  14125. this._deleteTimeQuery(token._startTimeQuery);
  14126. this._deleteTimeQuery(token._endTimeQuery);
  14127. token._startTimeQuery = null;
  14128. token._endTimeQuery = null;
  14129. }
  14130. else {
  14131. if (!token._timeElapsedQuery) {
  14132. return -1;
  14133. }
  14134. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14135. this._deleteTimeQuery(token._timeElapsedQuery);
  14136. token._timeElapsedQuery = null;
  14137. token._timeElapsedQueryEnded = false;
  14138. this._currentNonTimestampToken = null;
  14139. }
  14140. return result;
  14141. }
  14142. return -1;
  14143. };
  14144. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14145. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14146. };
  14147. // Transform feedback
  14148. Engine.prototype.createTransformFeedback = function () {
  14149. return this._gl.createTransformFeedback();
  14150. };
  14151. Engine.prototype.deleteTransformFeedback = function (value) {
  14152. this._gl.deleteTransformFeedback(value);
  14153. };
  14154. Engine.prototype.bindTransformFeedback = function (value) {
  14155. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14156. };
  14157. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14158. if (usePoints === void 0) { usePoints = true; }
  14159. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14160. };
  14161. Engine.prototype.endTransformFeedback = function () {
  14162. this._gl.endTransformFeedback();
  14163. };
  14164. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14165. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14166. };
  14167. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14168. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14169. };
  14170. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14171. var _this = this;
  14172. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14173. this._activeRequests.push(request);
  14174. request.onCompleteObservable.add(function (request) {
  14175. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14176. });
  14177. return request;
  14178. };
  14179. /** @ignore */
  14180. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14181. var _this = this;
  14182. return new Promise(function (resolve, reject) {
  14183. _this._loadFile(url, function (data) {
  14184. resolve(data);
  14185. }, undefined, database, useArrayBuffer, function (request, exception) {
  14186. reject(exception);
  14187. });
  14188. });
  14189. };
  14190. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14191. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14192. var onload = function (data) {
  14193. loadedFiles[index] = data;
  14194. loadedFiles._internalCount++;
  14195. if (loadedFiles._internalCount === 6) {
  14196. onfinish(loadedFiles);
  14197. }
  14198. };
  14199. var onerror = function (request, exception) {
  14200. if (onErrorCallBack && request) {
  14201. onErrorCallBack(request.status + " " + request.statusText, exception);
  14202. }
  14203. };
  14204. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14205. };
  14206. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14207. if (onError === void 0) { onError = null; }
  14208. var loadedFiles = [];
  14209. loadedFiles._internalCount = 0;
  14210. for (var index = 0; index < 6; index++) {
  14211. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14212. }
  14213. };
  14214. // Statics
  14215. Engine.isSupported = function () {
  14216. try {
  14217. var tempcanvas = document.createElement("canvas");
  14218. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14219. return gl != null && !!window.WebGLRenderingContext;
  14220. }
  14221. catch (e) {
  14222. return false;
  14223. }
  14224. };
  14225. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14226. Engine.ExceptionList = [
  14227. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14228. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14229. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14230. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14231. ];
  14232. Engine.Instances = new Array();
  14233. // Const statics
  14234. Engine._ALPHA_DISABLE = 0;
  14235. Engine._ALPHA_ADD = 1;
  14236. Engine._ALPHA_COMBINE = 2;
  14237. Engine._ALPHA_SUBTRACT = 3;
  14238. Engine._ALPHA_MULTIPLY = 4;
  14239. Engine._ALPHA_MAXIMIZED = 5;
  14240. Engine._ALPHA_ONEONE = 6;
  14241. Engine._ALPHA_PREMULTIPLIED = 7;
  14242. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14243. Engine._ALPHA_INTERPOLATE = 9;
  14244. Engine._ALPHA_SCREENMODE = 10;
  14245. Engine._DELAYLOADSTATE_NONE = 0;
  14246. Engine._DELAYLOADSTATE_LOADED = 1;
  14247. Engine._DELAYLOADSTATE_LOADING = 2;
  14248. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14249. Engine._TEXTUREFORMAT_ALPHA = 0;
  14250. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14251. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14252. Engine._TEXTUREFORMAT_RGB = 4;
  14253. Engine._TEXTUREFORMAT_RGBA = 5;
  14254. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14255. Engine._TEXTURETYPE_FLOAT = 1;
  14256. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14257. // Depht or Stencil test Constants.
  14258. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14259. 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.
  14260. 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.
  14261. 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.
  14262. 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.
  14263. 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.
  14264. 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.
  14265. 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.
  14266. // Stencil Actions Constants.
  14267. Engine._KEEP = 0x1E00;
  14268. Engine._REPLACE = 0x1E01;
  14269. Engine._INCR = 0x1E02;
  14270. Engine._DECR = 0x1E03;
  14271. Engine._INVERT = 0x150A;
  14272. Engine._INCR_WRAP = 0x8507;
  14273. Engine._DECR_WRAP = 0x8508;
  14274. // Texture rescaling mode
  14275. Engine._SCALEMODE_FLOOR = 1;
  14276. Engine._SCALEMODE_NEAREST = 2;
  14277. Engine._SCALEMODE_CEILING = 3;
  14278. // Updatable statics so stick with vars here
  14279. Engine.CollisionsEpsilon = 0.001;
  14280. Engine.CodeRepository = "src/";
  14281. Engine.ShadersRepository = "src/Shaders/";
  14282. return Engine;
  14283. }());
  14284. BABYLON.Engine = Engine;
  14285. })(BABYLON || (BABYLON = {}));
  14286. //# sourceMappingURL=babylon.engine.js.map
  14287. var BABYLON;
  14288. (function (BABYLON) {
  14289. /**
  14290. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14291. */
  14292. var Node = /** @class */ (function () {
  14293. /**
  14294. * @constructor
  14295. * @param {string} name - the name and id to be given to this node
  14296. * @param {BABYLON.Scene} the scene this node will be added to
  14297. */
  14298. function Node(name, scene) {
  14299. if (scene === void 0) { scene = null; }
  14300. this.state = "";
  14301. this.metadata = null;
  14302. this.doNotSerialize = false;
  14303. this.animations = new Array();
  14304. this._ranges = {};
  14305. this._isEnabled = true;
  14306. this._isReady = true;
  14307. this._currentRenderId = -1;
  14308. this._parentRenderId = -1;
  14309. /**
  14310. * An event triggered when the mesh is disposed.
  14311. * @type {BABYLON.Observable}
  14312. */
  14313. this.onDisposeObservable = new BABYLON.Observable();
  14314. // Behaviors
  14315. this._behaviors = new Array();
  14316. this.name = name;
  14317. this.id = name;
  14318. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14319. this.uniqueId = this._scene.getUniqueId();
  14320. this._initCache();
  14321. }
  14322. Object.defineProperty(Node.prototype, "parent", {
  14323. get: function () {
  14324. return this._parentNode;
  14325. },
  14326. set: function (parent) {
  14327. if (this._parentNode === parent) {
  14328. return;
  14329. }
  14330. // Remove self from list of children of parent
  14331. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14332. var index = this._parentNode._children.indexOf(this);
  14333. if (index !== -1) {
  14334. this._parentNode._children.splice(index, 1);
  14335. }
  14336. }
  14337. // Store new parent
  14338. this._parentNode = parent;
  14339. // Add as child to new parent
  14340. if (this._parentNode) {
  14341. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14342. this._parentNode._children = new Array();
  14343. }
  14344. this._parentNode._children.push(this);
  14345. }
  14346. },
  14347. enumerable: true,
  14348. configurable: true
  14349. });
  14350. Node.prototype.getClassName = function () {
  14351. return "Node";
  14352. };
  14353. Object.defineProperty(Node.prototype, "onDispose", {
  14354. set: function (callback) {
  14355. if (this._onDisposeObserver) {
  14356. this.onDisposeObservable.remove(this._onDisposeObserver);
  14357. }
  14358. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Node.prototype.getScene = function () {
  14364. return this._scene;
  14365. };
  14366. Node.prototype.getEngine = function () {
  14367. return this._scene.getEngine();
  14368. };
  14369. Node.prototype.addBehavior = function (behavior) {
  14370. var _this = this;
  14371. var index = this._behaviors.indexOf(behavior);
  14372. if (index !== -1) {
  14373. return this;
  14374. }
  14375. behavior.init();
  14376. if (this._scene.isLoading) {
  14377. // We defer the attach when the scene will be loaded
  14378. var observer = this._scene.onDataLoadedObservable.add(function () {
  14379. behavior.attach(_this);
  14380. setTimeout(function () {
  14381. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14382. _this._scene.onDataLoadedObservable.remove(observer);
  14383. }, 0);
  14384. });
  14385. }
  14386. else {
  14387. behavior.attach(this);
  14388. }
  14389. this._behaviors.push(behavior);
  14390. return this;
  14391. };
  14392. Node.prototype.removeBehavior = function (behavior) {
  14393. var index = this._behaviors.indexOf(behavior);
  14394. if (index === -1) {
  14395. return this;
  14396. }
  14397. this._behaviors[index].detach();
  14398. this._behaviors.splice(index, 1);
  14399. return this;
  14400. };
  14401. Object.defineProperty(Node.prototype, "behaviors", {
  14402. get: function () {
  14403. return this._behaviors;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Node.prototype.getBehaviorByName = function (name) {
  14409. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14410. var behavior = _a[_i];
  14411. if (behavior.name === name) {
  14412. return behavior;
  14413. }
  14414. }
  14415. return null;
  14416. };
  14417. // override it in derived class
  14418. Node.prototype.getWorldMatrix = function () {
  14419. return BABYLON.Matrix.Identity();
  14420. };
  14421. // override it in derived class if you add new variables to the cache
  14422. // and call the parent class method
  14423. Node.prototype._initCache = function () {
  14424. this._cache = {};
  14425. this._cache.parent = undefined;
  14426. };
  14427. Node.prototype.updateCache = function (force) {
  14428. if (!force && this.isSynchronized())
  14429. return;
  14430. this._cache.parent = this.parent;
  14431. this._updateCache();
  14432. };
  14433. // override it in derived class if you add new variables to the cache
  14434. // and call the parent class method if !ignoreParentClass
  14435. Node.prototype._updateCache = function (ignoreParentClass) {
  14436. };
  14437. // override it in derived class if you add new variables to the cache
  14438. Node.prototype._isSynchronized = function () {
  14439. return true;
  14440. };
  14441. Node.prototype._markSyncedWithParent = function () {
  14442. if (this.parent) {
  14443. this._parentRenderId = this.parent._currentRenderId;
  14444. }
  14445. };
  14446. Node.prototype.isSynchronizedWithParent = function () {
  14447. if (!this.parent) {
  14448. return true;
  14449. }
  14450. if (this._parentRenderId !== this.parent._currentRenderId) {
  14451. return false;
  14452. }
  14453. return this.parent.isSynchronized();
  14454. };
  14455. Node.prototype.isSynchronized = function (updateCache) {
  14456. var check = this.hasNewParent();
  14457. check = check || !this.isSynchronizedWithParent();
  14458. check = check || !this._isSynchronized();
  14459. if (updateCache)
  14460. this.updateCache(true);
  14461. return !check;
  14462. };
  14463. Node.prototype.hasNewParent = function (update) {
  14464. if (this._cache.parent === this.parent)
  14465. return false;
  14466. if (update)
  14467. this._cache.parent = this.parent;
  14468. return true;
  14469. };
  14470. /**
  14471. * Is this node ready to be used/rendered
  14472. * @return {boolean} is it ready
  14473. */
  14474. Node.prototype.isReady = function () {
  14475. return this._isReady;
  14476. };
  14477. /**
  14478. * Is this node enabled.
  14479. * 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.
  14480. * @param {boolean} [checkAncestors=true] - 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.
  14481. * @return {boolean} whether this node (and its parent) is enabled.
  14482. * @see setEnabled
  14483. */
  14484. Node.prototype.isEnabled = function (checkAncestors) {
  14485. if (checkAncestors === void 0) { checkAncestors = true; }
  14486. if (checkAncestors === false) {
  14487. return this._isEnabled;
  14488. }
  14489. if (this._isEnabled === false) {
  14490. return false;
  14491. }
  14492. if (this.parent !== undefined && this.parent !== null) {
  14493. return this.parent.isEnabled(checkAncestors);
  14494. }
  14495. return true;
  14496. };
  14497. /**
  14498. * Set the enabled state of this node.
  14499. * @param {boolean} value - the new enabled state
  14500. * @see isEnabled
  14501. */
  14502. Node.prototype.setEnabled = function (value) {
  14503. this._isEnabled = value;
  14504. };
  14505. /**
  14506. * Is this node a descendant of the given node.
  14507. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14508. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14509. * @see parent
  14510. */
  14511. Node.prototype.isDescendantOf = function (ancestor) {
  14512. if (this.parent) {
  14513. if (this.parent === ancestor) {
  14514. return true;
  14515. }
  14516. return this.parent.isDescendantOf(ancestor);
  14517. }
  14518. return false;
  14519. };
  14520. /**
  14521. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14522. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14523. * @param {boolean} directDescendantsOnly 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.
  14524. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14525. */
  14526. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14527. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14528. if (!this._children) {
  14529. return;
  14530. }
  14531. for (var index = 0; index < this._children.length; index++) {
  14532. var item = this._children[index];
  14533. if (!predicate || predicate(item)) {
  14534. results.push(item);
  14535. }
  14536. if (!directDescendantsOnly) {
  14537. item._getDescendants(results, false, predicate);
  14538. }
  14539. }
  14540. };
  14541. /**
  14542. * Will return all nodes that have this node as ascendant.
  14543. * @param {boolean} directDescendantsOnly 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.
  14544. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14545. * @return {BABYLON.Node[]} all children nodes of all types.
  14546. */
  14547. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14548. var results = new Array();
  14549. this._getDescendants(results, directDescendantsOnly, predicate);
  14550. return results;
  14551. };
  14552. /**
  14553. * Get all child-meshes of this node.
  14554. */
  14555. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14556. var results = [];
  14557. this._getDescendants(results, directDescendantsOnly, function (node) {
  14558. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14559. });
  14560. return results;
  14561. };
  14562. /**
  14563. * Get all child-transformNodes of this node.
  14564. */
  14565. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14566. var results = [];
  14567. this._getDescendants(results, directDescendantsOnly, function (node) {
  14568. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14569. });
  14570. return results;
  14571. };
  14572. /**
  14573. * Get all direct children of this node.
  14574. */
  14575. Node.prototype.getChildren = function (predicate) {
  14576. return this.getDescendants(true, predicate);
  14577. };
  14578. Node.prototype._setReady = function (state) {
  14579. if (state === this._isReady) {
  14580. return;
  14581. }
  14582. if (!state) {
  14583. this._isReady = false;
  14584. return;
  14585. }
  14586. this._isReady = true;
  14587. if (this.onReady) {
  14588. this.onReady(this);
  14589. }
  14590. };
  14591. Node.prototype.getAnimationByName = function (name) {
  14592. for (var i = 0; i < this.animations.length; i++) {
  14593. var animation = this.animations[i];
  14594. if (animation.name === name) {
  14595. return animation;
  14596. }
  14597. }
  14598. return null;
  14599. };
  14600. Node.prototype.createAnimationRange = function (name, from, to) {
  14601. // check name not already in use
  14602. if (!this._ranges[name]) {
  14603. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14604. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14605. if (this.animations[i]) {
  14606. this.animations[i].createRange(name, from, to);
  14607. }
  14608. }
  14609. }
  14610. };
  14611. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14612. if (deleteFrames === void 0) { deleteFrames = true; }
  14613. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14614. if (this.animations[i]) {
  14615. this.animations[i].deleteRange(name, deleteFrames);
  14616. }
  14617. }
  14618. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14619. };
  14620. Node.prototype.getAnimationRange = function (name) {
  14621. return this._ranges[name];
  14622. };
  14623. /**
  14624. * Will start the animation sequence
  14625. * @param name defines the range frames for animation sequence
  14626. * @param loop defines if the animation should loop (false by default)
  14627. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  14628. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  14629. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  14630. */
  14631. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14632. var range = this.getAnimationRange(name);
  14633. if (!range) {
  14634. return null;
  14635. }
  14636. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14637. };
  14638. Node.prototype.serializeAnimationRanges = function () {
  14639. var serializationRanges = [];
  14640. for (var name in this._ranges) {
  14641. var localRange = this._ranges[name];
  14642. if (!localRange) {
  14643. continue;
  14644. }
  14645. var range = {};
  14646. range.name = name;
  14647. range.from = localRange.from;
  14648. range.to = localRange.to;
  14649. serializationRanges.push(range);
  14650. }
  14651. return serializationRanges;
  14652. };
  14653. // override it in derived class
  14654. Node.prototype.computeWorldMatrix = function (force) {
  14655. return BABYLON.Matrix.Identity();
  14656. };
  14657. Node.prototype.dispose = function () {
  14658. this.parent = null;
  14659. // Callback
  14660. this.onDisposeObservable.notifyObservers(this);
  14661. this.onDisposeObservable.clear();
  14662. // Behaviors
  14663. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14664. var behavior = _a[_i];
  14665. behavior.detach();
  14666. }
  14667. this._behaviors = [];
  14668. };
  14669. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14670. if (parsedNode.ranges) {
  14671. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14672. var data = parsedNode.ranges[index];
  14673. node.createAnimationRange(data.name, data.from, data.to);
  14674. }
  14675. }
  14676. };
  14677. __decorate([
  14678. BABYLON.serialize()
  14679. ], Node.prototype, "name", void 0);
  14680. __decorate([
  14681. BABYLON.serialize()
  14682. ], Node.prototype, "id", void 0);
  14683. __decorate([
  14684. BABYLON.serialize()
  14685. ], Node.prototype, "uniqueId", void 0);
  14686. __decorate([
  14687. BABYLON.serialize()
  14688. ], Node.prototype, "state", void 0);
  14689. __decorate([
  14690. BABYLON.serialize()
  14691. ], Node.prototype, "metadata", void 0);
  14692. return Node;
  14693. }());
  14694. BABYLON.Node = Node;
  14695. })(BABYLON || (BABYLON = {}));
  14696. //# sourceMappingURL=babylon.node.js.map
  14697. var BABYLON;
  14698. (function (BABYLON) {
  14699. var BoundingSphere = /** @class */ (function () {
  14700. function BoundingSphere(minimum, maximum) {
  14701. this.minimum = minimum;
  14702. this.maximum = maximum;
  14703. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14704. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14705. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14706. this.radius = distance * 0.5;
  14707. this.centerWorld = BABYLON.Vector3.Zero();
  14708. this._update(BABYLON.Matrix.Identity());
  14709. }
  14710. // Methods
  14711. BoundingSphere.prototype._update = function (world) {
  14712. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14713. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14714. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14715. };
  14716. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14717. for (var i = 0; i < 6; i++) {
  14718. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14719. return false;
  14720. }
  14721. return true;
  14722. };
  14723. BoundingSphere.prototype.intersectsPoint = function (point) {
  14724. var x = this.centerWorld.x - point.x;
  14725. var y = this.centerWorld.y - point.y;
  14726. var z = this.centerWorld.z - point.z;
  14727. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14728. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14729. return false;
  14730. return true;
  14731. };
  14732. // Statics
  14733. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14734. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14735. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14736. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14737. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14738. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14739. return false;
  14740. return true;
  14741. };
  14742. return BoundingSphere;
  14743. }());
  14744. BABYLON.BoundingSphere = BoundingSphere;
  14745. })(BABYLON || (BABYLON = {}));
  14746. //# sourceMappingURL=babylon.boundingSphere.js.map
  14747. var BABYLON;
  14748. (function (BABYLON) {
  14749. var BoundingBox = /** @class */ (function () {
  14750. function BoundingBox(minimum, maximum) {
  14751. this.minimum = minimum;
  14752. this.maximum = maximum;
  14753. this.vectors = new Array();
  14754. this.vectorsWorld = new Array();
  14755. // Bounding vectors
  14756. this.vectors.push(this.minimum.clone());
  14757. this.vectors.push(this.maximum.clone());
  14758. this.vectors.push(this.minimum.clone());
  14759. this.vectors[2].x = this.maximum.x;
  14760. this.vectors.push(this.minimum.clone());
  14761. this.vectors[3].y = this.maximum.y;
  14762. this.vectors.push(this.minimum.clone());
  14763. this.vectors[4].z = this.maximum.z;
  14764. this.vectors.push(this.maximum.clone());
  14765. this.vectors[5].z = this.minimum.z;
  14766. this.vectors.push(this.maximum.clone());
  14767. this.vectors[6].x = this.minimum.x;
  14768. this.vectors.push(this.maximum.clone());
  14769. this.vectors[7].y = this.minimum.y;
  14770. // OBB
  14771. this.center = this.maximum.add(this.minimum).scale(0.5);
  14772. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14773. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14774. // World
  14775. for (var index = 0; index < this.vectors.length; index++) {
  14776. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14777. }
  14778. this.minimumWorld = BABYLON.Vector3.Zero();
  14779. this.maximumWorld = BABYLON.Vector3.Zero();
  14780. this.centerWorld = BABYLON.Vector3.Zero();
  14781. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14782. this._update(BABYLON.Matrix.Identity());
  14783. }
  14784. // Methods
  14785. BoundingBox.prototype.getWorldMatrix = function () {
  14786. return this._worldMatrix;
  14787. };
  14788. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14789. this._worldMatrix.copyFrom(matrix);
  14790. return this;
  14791. };
  14792. BoundingBox.prototype._update = function (world) {
  14793. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14794. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14795. for (var index = 0; index < this.vectors.length; index++) {
  14796. var v = this.vectorsWorld[index];
  14797. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14798. if (v.x < this.minimumWorld.x)
  14799. this.minimumWorld.x = v.x;
  14800. if (v.y < this.minimumWorld.y)
  14801. this.minimumWorld.y = v.y;
  14802. if (v.z < this.minimumWorld.z)
  14803. this.minimumWorld.z = v.z;
  14804. if (v.x > this.maximumWorld.x)
  14805. this.maximumWorld.x = v.x;
  14806. if (v.y > this.maximumWorld.y)
  14807. this.maximumWorld.y = v.y;
  14808. if (v.z > this.maximumWorld.z)
  14809. this.maximumWorld.z = v.z;
  14810. }
  14811. // Extend
  14812. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14813. this.extendSizeWorld.scaleInPlace(0.5);
  14814. // OBB
  14815. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14816. this.centerWorld.scaleInPlace(0.5);
  14817. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14818. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14819. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14820. this._worldMatrix = world;
  14821. };
  14822. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14823. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14824. };
  14825. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14826. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14827. };
  14828. BoundingBox.prototype.intersectsPoint = function (point) {
  14829. var delta = -BABYLON.Epsilon;
  14830. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14831. return false;
  14832. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14833. return false;
  14834. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14835. return false;
  14836. return true;
  14837. };
  14838. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14839. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14840. };
  14841. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14842. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14843. return false;
  14844. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14845. return false;
  14846. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14847. return false;
  14848. return true;
  14849. };
  14850. // Statics
  14851. BoundingBox.Intersects = function (box0, box1) {
  14852. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14853. return false;
  14854. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14855. return false;
  14856. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14857. return false;
  14858. return true;
  14859. };
  14860. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14861. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14862. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14863. return (num <= (sphereRadius * sphereRadius));
  14864. };
  14865. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14866. for (var p = 0; p < 6; p++) {
  14867. for (var i = 0; i < 8; i++) {
  14868. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14869. return false;
  14870. }
  14871. }
  14872. }
  14873. return true;
  14874. };
  14875. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14876. for (var p = 0; p < 6; p++) {
  14877. var inCount = 8;
  14878. for (var i = 0; i < 8; i++) {
  14879. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14880. --inCount;
  14881. }
  14882. else {
  14883. break;
  14884. }
  14885. }
  14886. if (inCount === 0)
  14887. return false;
  14888. }
  14889. return true;
  14890. };
  14891. return BoundingBox;
  14892. }());
  14893. BABYLON.BoundingBox = BoundingBox;
  14894. })(BABYLON || (BABYLON = {}));
  14895. //# sourceMappingURL=babylon.boundingBox.js.map
  14896. var BABYLON;
  14897. (function (BABYLON) {
  14898. var computeBoxExtents = function (axis, box) {
  14899. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14900. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14901. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14902. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14903. var r = r0 + r1 + r2;
  14904. return {
  14905. min: p - r,
  14906. max: p + r
  14907. };
  14908. };
  14909. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14910. var axisOverlap = function (axis, box0, box1) {
  14911. var result0 = computeBoxExtents(axis, box0);
  14912. var result1 = computeBoxExtents(axis, box1);
  14913. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14914. };
  14915. var BoundingInfo = /** @class */ (function () {
  14916. function BoundingInfo(minimum, maximum) {
  14917. this.minimum = minimum;
  14918. this.maximum = maximum;
  14919. this._isLocked = false;
  14920. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14921. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14922. }
  14923. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14924. get: function () {
  14925. return this._isLocked;
  14926. },
  14927. set: function (value) {
  14928. this._isLocked = value;
  14929. },
  14930. enumerable: true,
  14931. configurable: true
  14932. });
  14933. // Methods
  14934. BoundingInfo.prototype.update = function (world) {
  14935. if (this._isLocked) {
  14936. return;
  14937. }
  14938. this.boundingBox._update(world);
  14939. this.boundingSphere._update(world);
  14940. };
  14941. /**
  14942. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14943. * @param center New center of the bounding info
  14944. * @param extend New extend of the bounding info
  14945. */
  14946. BoundingInfo.prototype.centerOn = function (center, extend) {
  14947. this.minimum = center.subtract(extend);
  14948. this.maximum = center.add(extend);
  14949. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14950. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14951. return this;
  14952. };
  14953. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14954. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14955. return false;
  14956. return this.boundingBox.isInFrustum(frustumPlanes);
  14957. };
  14958. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14959. /**
  14960. * Gets the world distance between the min and max points of the bounding box
  14961. */
  14962. get: function () {
  14963. var boundingBox = this.boundingBox;
  14964. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14965. return size.length();
  14966. },
  14967. enumerable: true,
  14968. configurable: true
  14969. });
  14970. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14971. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14972. };
  14973. BoundingInfo.prototype._checkCollision = function (collider) {
  14974. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14975. };
  14976. BoundingInfo.prototype.intersectsPoint = function (point) {
  14977. if (!this.boundingSphere.centerWorld) {
  14978. return false;
  14979. }
  14980. if (!this.boundingSphere.intersectsPoint(point)) {
  14981. return false;
  14982. }
  14983. if (!this.boundingBox.intersectsPoint(point)) {
  14984. return false;
  14985. }
  14986. return true;
  14987. };
  14988. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14989. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14990. return false;
  14991. }
  14992. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14993. return false;
  14994. }
  14995. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14996. return false;
  14997. }
  14998. if (!precise) {
  14999. return true;
  15000. }
  15001. var box0 = this.boundingBox;
  15002. var box1 = boundingInfo.boundingBox;
  15003. if (!axisOverlap(box0.directions[0], box0, box1))
  15004. return false;
  15005. if (!axisOverlap(box0.directions[1], box0, box1))
  15006. return false;
  15007. if (!axisOverlap(box0.directions[2], box0, box1))
  15008. return false;
  15009. if (!axisOverlap(box1.directions[0], box0, box1))
  15010. return false;
  15011. if (!axisOverlap(box1.directions[1], box0, box1))
  15012. return false;
  15013. if (!axisOverlap(box1.directions[2], box0, box1))
  15014. return false;
  15015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15016. return false;
  15017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15018. return false;
  15019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15020. return false;
  15021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15022. return false;
  15023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15024. return false;
  15025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15026. return false;
  15027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15028. return false;
  15029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15030. return false;
  15031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15032. return false;
  15033. return true;
  15034. };
  15035. return BoundingInfo;
  15036. }());
  15037. BABYLON.BoundingInfo = BoundingInfo;
  15038. })(BABYLON || (BABYLON = {}));
  15039. //# sourceMappingURL=babylon.boundingInfo.js.map
  15040. var BABYLON;
  15041. (function (BABYLON) {
  15042. var TransformNode = /** @class */ (function (_super) {
  15043. __extends(TransformNode, _super);
  15044. function TransformNode(name, scene, isPure) {
  15045. if (scene === void 0) { scene = null; }
  15046. if (isPure === void 0) { isPure = true; }
  15047. var _this = _super.call(this, name, scene) || this;
  15048. // Properties
  15049. _this._rotation = BABYLON.Vector3.Zero();
  15050. _this._scaling = BABYLON.Vector3.One();
  15051. _this._isDirty = false;
  15052. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15053. _this.scalingDeterminant = 1;
  15054. _this.infiniteDistance = false;
  15055. _this.position = BABYLON.Vector3.Zero();
  15056. _this._localWorld = BABYLON.Matrix.Zero();
  15057. _this._worldMatrix = BABYLON.Matrix.Zero();
  15058. _this._worldMatrixDeterminant = 0;
  15059. _this._absolutePosition = BABYLON.Vector3.Zero();
  15060. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15061. _this._postMultiplyPivotMatrix = false;
  15062. _this._isWorldMatrixFrozen = false;
  15063. /**
  15064. * An event triggered after the world matrix is updated
  15065. * @type {BABYLON.Observable}
  15066. */
  15067. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15068. _this._nonUniformScaling = false;
  15069. if (isPure) {
  15070. _this.getScene().addTransformNode(_this);
  15071. }
  15072. return _this;
  15073. }
  15074. Object.defineProperty(TransformNode.prototype, "rotation", {
  15075. /**
  15076. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15077. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15078. * Default : (0.0, 0.0, 0.0)
  15079. */
  15080. get: function () {
  15081. return this._rotation;
  15082. },
  15083. set: function (newRotation) {
  15084. this._rotation = newRotation;
  15085. },
  15086. enumerable: true,
  15087. configurable: true
  15088. });
  15089. Object.defineProperty(TransformNode.prototype, "scaling", {
  15090. /**
  15091. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15092. * Default : (1.0, 1.0, 1.0)
  15093. */
  15094. get: function () {
  15095. return this._scaling;
  15096. },
  15097. /**
  15098. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15099. * Default : (1.0, 1.0, 1.0)
  15100. */
  15101. set: function (newScaling) {
  15102. this._scaling = newScaling;
  15103. },
  15104. enumerable: true,
  15105. configurable: true
  15106. });
  15107. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15108. /**
  15109. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15110. * It's null by default.
  15111. * 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)
  15112. */
  15113. get: function () {
  15114. return this._rotationQuaternion;
  15115. },
  15116. set: function (quaternion) {
  15117. this._rotationQuaternion = quaternion;
  15118. //reset the rotation vector.
  15119. if (quaternion && this.rotation.length()) {
  15120. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15121. }
  15122. },
  15123. enumerable: true,
  15124. configurable: true
  15125. });
  15126. /**
  15127. * Returns the latest update of the World matrix
  15128. * Returns a Matrix.
  15129. */
  15130. TransformNode.prototype.getWorldMatrix = function () {
  15131. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15132. this.computeWorldMatrix();
  15133. }
  15134. return this._worldMatrix;
  15135. };
  15136. /**
  15137. * Returns the latest update of the World matrix determinant.
  15138. */
  15139. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15140. return this._worldMatrixDeterminant;
  15141. };
  15142. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15143. /**
  15144. * Returns directly the latest state of the mesh World matrix.
  15145. * A Matrix is returned.
  15146. */
  15147. get: function () {
  15148. return this._worldMatrix;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. /**
  15154. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15155. * Returns the AbstractMesh.
  15156. */
  15157. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15158. this._poseMatrix.copyFrom(matrix);
  15159. return this;
  15160. };
  15161. /**
  15162. * Returns the mesh Pose matrix.
  15163. * Returned object : Matrix
  15164. */
  15165. TransformNode.prototype.getPoseMatrix = function () {
  15166. return this._poseMatrix;
  15167. };
  15168. TransformNode.prototype._isSynchronized = function () {
  15169. if (this._isDirty) {
  15170. return false;
  15171. }
  15172. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15173. return false;
  15174. if (this._cache.pivotMatrixUpdated) {
  15175. return false;
  15176. }
  15177. if (this.infiniteDistance) {
  15178. return false;
  15179. }
  15180. if (!this._cache.position.equals(this.position))
  15181. return false;
  15182. if (this.rotationQuaternion) {
  15183. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15184. return false;
  15185. }
  15186. if (!this._cache.rotation.equals(this.rotation))
  15187. return false;
  15188. if (!this._cache.scaling.equals(this.scaling))
  15189. return false;
  15190. return true;
  15191. };
  15192. TransformNode.prototype._initCache = function () {
  15193. _super.prototype._initCache.call(this);
  15194. this._cache.localMatrixUpdated = false;
  15195. this._cache.position = BABYLON.Vector3.Zero();
  15196. this._cache.scaling = BABYLON.Vector3.Zero();
  15197. this._cache.rotation = BABYLON.Vector3.Zero();
  15198. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15199. this._cache.billboardMode = -1;
  15200. };
  15201. TransformNode.prototype.markAsDirty = function (property) {
  15202. if (property === "rotation") {
  15203. this.rotationQuaternion = null;
  15204. }
  15205. this._currentRenderId = Number.MAX_VALUE;
  15206. this._isDirty = true;
  15207. return this;
  15208. };
  15209. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15210. /**
  15211. * Returns the current mesh absolute position.
  15212. * Retuns a Vector3.
  15213. */
  15214. get: function () {
  15215. return this._absolutePosition;
  15216. },
  15217. enumerable: true,
  15218. configurable: true
  15219. });
  15220. /**
  15221. * Sets a new matrix to apply before all other transformation
  15222. * @param matrix defines the transform matrix
  15223. * @returns the current TransformNode
  15224. */
  15225. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15226. return this.setPivotMatrix(matrix, false);
  15227. };
  15228. /**
  15229. * Sets a new pivot matrix to the current node
  15230. * @param matrix defines the new pivot matrix to use
  15231. * @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
  15232. * @returns the current TransformNode
  15233. */
  15234. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15235. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15236. this._pivotMatrix = matrix.clone();
  15237. this._cache.pivotMatrixUpdated = true;
  15238. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15239. if (this._postMultiplyPivotMatrix) {
  15240. if (!this._pivotMatrixInverse) {
  15241. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15242. }
  15243. else {
  15244. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15245. }
  15246. }
  15247. return this;
  15248. };
  15249. /**
  15250. * Returns the mesh pivot matrix.
  15251. * Default : Identity.
  15252. * A Matrix is returned.
  15253. */
  15254. TransformNode.prototype.getPivotMatrix = function () {
  15255. return this._pivotMatrix;
  15256. };
  15257. /**
  15258. * Prevents the World matrix to be computed any longer.
  15259. * Returns the AbstractMesh.
  15260. */
  15261. TransformNode.prototype.freezeWorldMatrix = function () {
  15262. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15263. this.computeWorldMatrix(true);
  15264. this._isWorldMatrixFrozen = true;
  15265. return this;
  15266. };
  15267. /**
  15268. * Allows back the World matrix computation.
  15269. * Returns the AbstractMesh.
  15270. */
  15271. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15272. this._isWorldMatrixFrozen = false;
  15273. this.computeWorldMatrix(true);
  15274. return this;
  15275. };
  15276. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15277. /**
  15278. * True if the World matrix has been frozen.
  15279. * Returns a boolean.
  15280. */
  15281. get: function () {
  15282. return this._isWorldMatrixFrozen;
  15283. },
  15284. enumerable: true,
  15285. configurable: true
  15286. });
  15287. /**
  15288. * Retuns the mesh absolute position in the World.
  15289. * Returns a Vector3.
  15290. */
  15291. TransformNode.prototype.getAbsolutePosition = function () {
  15292. this.computeWorldMatrix();
  15293. return this._absolutePosition;
  15294. };
  15295. /**
  15296. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15297. * Returns the AbstractMesh.
  15298. */
  15299. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15300. if (!absolutePosition) {
  15301. return this;
  15302. }
  15303. var absolutePositionX;
  15304. var absolutePositionY;
  15305. var absolutePositionZ;
  15306. if (absolutePosition.x === undefined) {
  15307. if (arguments.length < 3) {
  15308. return this;
  15309. }
  15310. absolutePositionX = arguments[0];
  15311. absolutePositionY = arguments[1];
  15312. absolutePositionZ = arguments[2];
  15313. }
  15314. else {
  15315. absolutePositionX = absolutePosition.x;
  15316. absolutePositionY = absolutePosition.y;
  15317. absolutePositionZ = absolutePosition.z;
  15318. }
  15319. if (this.parent) {
  15320. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15321. invertParentWorldMatrix.invert();
  15322. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15323. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15324. }
  15325. else {
  15326. this.position.x = absolutePositionX;
  15327. this.position.y = absolutePositionY;
  15328. this.position.z = absolutePositionZ;
  15329. }
  15330. return this;
  15331. };
  15332. /**
  15333. * Sets the mesh position in its local space.
  15334. * Returns the AbstractMesh.
  15335. */
  15336. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15337. this.computeWorldMatrix();
  15338. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15339. return this;
  15340. };
  15341. /**
  15342. * Returns the mesh position in the local space from the current World matrix values.
  15343. * Returns a new Vector3.
  15344. */
  15345. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15346. this.computeWorldMatrix();
  15347. var invLocalWorldMatrix = this._localWorld.clone();
  15348. invLocalWorldMatrix.invert();
  15349. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15350. };
  15351. /**
  15352. * Translates the mesh along the passed Vector3 in its local space.
  15353. * Returns the AbstractMesh.
  15354. */
  15355. TransformNode.prototype.locallyTranslate = function (vector3) {
  15356. this.computeWorldMatrix(true);
  15357. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15358. return this;
  15359. };
  15360. /**
  15361. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15362. * @param targetPoint the position (must be in same space as current mesh) to look at
  15363. * @param yawCor optional yaw (y-axis) correction in radians
  15364. * @param pitchCor optional pitch (x-axis) correction in radians
  15365. * @param rollCor optional roll (z-axis) correction in radians
  15366. * @param space the choosen space of the target
  15367. * @returns the TransformNode.
  15368. */
  15369. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15370. if (yawCor === void 0) { yawCor = 0; }
  15371. if (pitchCor === void 0) { pitchCor = 0; }
  15372. if (rollCor === void 0) { rollCor = 0; }
  15373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15374. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15375. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15376. targetPoint.subtractToRef(pos, dv);
  15377. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15378. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15379. var pitch = Math.atan2(dv.y, len);
  15380. if (this.rotationQuaternion) {
  15381. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15382. }
  15383. else {
  15384. this.rotation.x = pitch + pitchCor;
  15385. this.rotation.y = yaw + yawCor;
  15386. this.rotation.z = rollCor;
  15387. }
  15388. return this;
  15389. };
  15390. /**
  15391. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15392. * This Vector3 is expressed in the World space.
  15393. */
  15394. TransformNode.prototype.getDirection = function (localAxis) {
  15395. var result = BABYLON.Vector3.Zero();
  15396. this.getDirectionToRef(localAxis, result);
  15397. return result;
  15398. };
  15399. /**
  15400. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15401. * localAxis is expressed in the mesh local space.
  15402. * result is computed in the Wordl space from the mesh World matrix.
  15403. * Returns the AbstractMesh.
  15404. */
  15405. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15406. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15407. return this;
  15408. };
  15409. /**
  15410. * Sets a new pivot point to the current node
  15411. * @param point defines the new pivot point to use
  15412. * @param space defines if the point is in world or local space (local by default)
  15413. * @returns the current TransformNode
  15414. */
  15415. TransformNode.prototype.setPivotPoint = function (point, space) {
  15416. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15417. if (this.getScene().getRenderId() == 0) {
  15418. this.computeWorldMatrix(true);
  15419. }
  15420. var wm = this.getWorldMatrix();
  15421. if (space == BABYLON.Space.WORLD) {
  15422. var tmat = BABYLON.Tmp.Matrix[0];
  15423. wm.invertToRef(tmat);
  15424. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15425. }
  15426. return this.setPivotMatrix(BABYLON.Matrix.Translation(point.x, point.y, point.z), true);
  15427. };
  15428. /**
  15429. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15430. */
  15431. TransformNode.prototype.getPivotPoint = function () {
  15432. var point = BABYLON.Vector3.Zero();
  15433. this.getPivotPointToRef(point);
  15434. return point;
  15435. };
  15436. /**
  15437. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15438. * Returns the AbstractMesh.
  15439. */
  15440. TransformNode.prototype.getPivotPointToRef = function (result) {
  15441. result.x = -this._pivotMatrix.m[12];
  15442. result.y = -this._pivotMatrix.m[13];
  15443. result.z = -this._pivotMatrix.m[14];
  15444. return this;
  15445. };
  15446. /**
  15447. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15448. */
  15449. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15450. var point = BABYLON.Vector3.Zero();
  15451. this.getAbsolutePivotPointToRef(point);
  15452. return point;
  15453. };
  15454. /**
  15455. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15456. * Returns the AbstractMesh.
  15457. */
  15458. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15459. result.x = this._pivotMatrix.m[12];
  15460. result.y = this._pivotMatrix.m[13];
  15461. result.z = this._pivotMatrix.m[14];
  15462. this.getPivotPointToRef(result);
  15463. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15464. return this;
  15465. };
  15466. /**
  15467. * Defines the passed node as the parent of the current node.
  15468. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15469. * Returns the TransformNode.
  15470. */
  15471. TransformNode.prototype.setParent = function (node) {
  15472. if (node === null) {
  15473. var rotation = BABYLON.Tmp.Quaternion[0];
  15474. var position = BABYLON.Tmp.Vector3[0];
  15475. var scale = BABYLON.Tmp.Vector3[1];
  15476. if (this.parent && this.parent.computeWorldMatrix) {
  15477. this.parent.computeWorldMatrix(true);
  15478. }
  15479. this.computeWorldMatrix(true);
  15480. this.getWorldMatrix().decompose(scale, rotation, position);
  15481. if (this.rotationQuaternion) {
  15482. this.rotationQuaternion.copyFrom(rotation);
  15483. }
  15484. else {
  15485. rotation.toEulerAnglesToRef(this.rotation);
  15486. }
  15487. this.scaling.x = scale.x;
  15488. this.scaling.y = scale.y;
  15489. this.scaling.z = scale.z;
  15490. this.position.x = position.x;
  15491. this.position.y = position.y;
  15492. this.position.z = position.z;
  15493. }
  15494. else {
  15495. var rotation = BABYLON.Tmp.Quaternion[0];
  15496. var position = BABYLON.Tmp.Vector3[0];
  15497. var scale = BABYLON.Tmp.Vector3[1];
  15498. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15499. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15500. this.computeWorldMatrix(true);
  15501. node.computeWorldMatrix(true);
  15502. node.getWorldMatrix().invertToRef(invParentMatrix);
  15503. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15504. diffMatrix.decompose(scale, rotation, position);
  15505. if (this.rotationQuaternion) {
  15506. this.rotationQuaternion.copyFrom(rotation);
  15507. }
  15508. else {
  15509. rotation.toEulerAnglesToRef(this.rotation);
  15510. }
  15511. this.position.x = position.x;
  15512. this.position.y = position.y;
  15513. this.position.z = position.z;
  15514. this.scaling.x = scale.x;
  15515. this.scaling.y = scale.y;
  15516. this.scaling.z = scale.z;
  15517. }
  15518. this.parent = node;
  15519. return this;
  15520. };
  15521. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15522. get: function () {
  15523. return this._nonUniformScaling;
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15529. if (this._nonUniformScaling === value) {
  15530. return false;
  15531. }
  15532. this._nonUniformScaling = true;
  15533. return true;
  15534. };
  15535. /**
  15536. * Attach the current TransformNode to another TransformNode associated with a bone
  15537. * @param bone Bone affecting the TransformNode
  15538. * @param affectedTransformNode TransformNode associated with the bone
  15539. */
  15540. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15541. this._transformToBoneReferal = affectedTransformNode;
  15542. this.parent = bone;
  15543. if (bone.getWorldMatrix().determinant() < 0) {
  15544. this.scalingDeterminant *= -1;
  15545. }
  15546. return this;
  15547. };
  15548. TransformNode.prototype.detachFromBone = function () {
  15549. if (!this.parent) {
  15550. return this;
  15551. }
  15552. if (this.parent.getWorldMatrix().determinant() < 0) {
  15553. this.scalingDeterminant *= -1;
  15554. }
  15555. this._transformToBoneReferal = null;
  15556. this.parent = null;
  15557. return this;
  15558. };
  15559. /**
  15560. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15561. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15562. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15563. * The passed axis is also normalized.
  15564. * Returns the AbstractMesh.
  15565. */
  15566. TransformNode.prototype.rotate = function (axis, amount, space) {
  15567. axis.normalize();
  15568. if (!this.rotationQuaternion) {
  15569. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15570. this.rotation = BABYLON.Vector3.Zero();
  15571. }
  15572. var rotationQuaternion;
  15573. if (!space || space === BABYLON.Space.LOCAL) {
  15574. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15575. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15576. }
  15577. else {
  15578. if (this.parent) {
  15579. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15580. invertParentWorldMatrix.invert();
  15581. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15582. }
  15583. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15584. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15585. }
  15586. return this;
  15587. };
  15588. /**
  15589. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15590. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15591. * The passed axis is also normalized.
  15592. * Returns the AbstractMesh.
  15593. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15594. */
  15595. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15596. axis.normalize();
  15597. if (!this.rotationQuaternion) {
  15598. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15599. this.rotation.copyFromFloats(0, 0, 0);
  15600. }
  15601. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15602. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15603. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15604. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15605. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15606. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15607. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15608. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15609. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15610. return this;
  15611. };
  15612. /**
  15613. * Translates the mesh along the axis vector for the passed distance in the given space.
  15614. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15615. * Returns the AbstractMesh.
  15616. */
  15617. TransformNode.prototype.translate = function (axis, distance, space) {
  15618. var displacementVector = axis.scale(distance);
  15619. if (!space || space === BABYLON.Space.LOCAL) {
  15620. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15621. this.setPositionWithLocalVector(tempV3);
  15622. }
  15623. else {
  15624. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15625. }
  15626. return this;
  15627. };
  15628. /**
  15629. * Adds a rotation step to the mesh current rotation.
  15630. * x, y, z are Euler angles expressed in radians.
  15631. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15632. * This means this rotation is made in the mesh local space only.
  15633. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15634. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15635. * ```javascript
  15636. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15637. * ```
  15638. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15639. * 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.
  15640. * Returns the AbstractMesh.
  15641. */
  15642. TransformNode.prototype.addRotation = function (x, y, z) {
  15643. var rotationQuaternion;
  15644. if (this.rotationQuaternion) {
  15645. rotationQuaternion = this.rotationQuaternion;
  15646. }
  15647. else {
  15648. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15649. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15650. }
  15651. var accumulation = BABYLON.Tmp.Quaternion[0];
  15652. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15653. rotationQuaternion.multiplyInPlace(accumulation);
  15654. if (!this.rotationQuaternion) {
  15655. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15656. }
  15657. return this;
  15658. };
  15659. /**
  15660. * Computes the mesh World matrix and returns it.
  15661. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15662. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15663. * If the parameter `force`is set to `true`, the actual computation is done.
  15664. * Returns the mesh World Matrix.
  15665. */
  15666. TransformNode.prototype.computeWorldMatrix = function (force) {
  15667. if (this._isWorldMatrixFrozen) {
  15668. return this._worldMatrix;
  15669. }
  15670. if (!force && this.isSynchronized(true)) {
  15671. return this._worldMatrix;
  15672. }
  15673. this._cache.position.copyFrom(this.position);
  15674. this._cache.scaling.copyFrom(this.scaling);
  15675. this._cache.pivotMatrixUpdated = false;
  15676. this._cache.billboardMode = this.billboardMode;
  15677. this._currentRenderId = this.getScene().getRenderId();
  15678. this._isDirty = false;
  15679. // Scaling
  15680. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15681. // Rotation
  15682. //rotate, if quaternion is set and rotation was used
  15683. if (this.rotationQuaternion) {
  15684. var len = this.rotation.length();
  15685. if (len) {
  15686. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15687. this.rotation.copyFromFloats(0, 0, 0);
  15688. }
  15689. }
  15690. if (this.rotationQuaternion) {
  15691. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15692. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15693. }
  15694. else {
  15695. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15696. this._cache.rotation.copyFrom(this.rotation);
  15697. }
  15698. // Translation
  15699. var camera = this.getScene().activeCamera;
  15700. if (this.infiniteDistance && !this.parent && camera) {
  15701. var cameraWorldMatrix = camera.getWorldMatrix();
  15702. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15703. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15704. }
  15705. else {
  15706. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15707. }
  15708. // Composing transformations
  15709. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15710. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15711. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15712. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15713. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15714. // Need to decompose each rotation here
  15715. var currentPosition = BABYLON.Tmp.Vector3[3];
  15716. if (this.parent && this.parent.getWorldMatrix) {
  15717. if (this._transformToBoneReferal) {
  15718. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15719. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15720. }
  15721. else {
  15722. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15723. }
  15724. }
  15725. else {
  15726. currentPosition.copyFrom(this.position);
  15727. }
  15728. currentPosition.subtractInPlace(camera.globalPosition);
  15729. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15730. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15731. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15732. }
  15733. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15734. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15735. }
  15736. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15737. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15738. }
  15739. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15740. }
  15741. else {
  15742. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15743. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15744. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15745. }
  15746. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15747. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15748. }
  15749. // Local world
  15750. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15751. // Parent
  15752. if (this.parent && this.parent.getWorldMatrix) {
  15753. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15754. if (this._transformToBoneReferal) {
  15755. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15756. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15757. }
  15758. else {
  15759. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15760. }
  15761. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15762. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15763. this._worldMatrix.copyFrom(this._localWorld);
  15764. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15765. }
  15766. else {
  15767. if (this._transformToBoneReferal) {
  15768. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15769. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15770. }
  15771. else {
  15772. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15773. }
  15774. }
  15775. this._markSyncedWithParent();
  15776. }
  15777. else {
  15778. this._worldMatrix.copyFrom(this._localWorld);
  15779. }
  15780. // Post multiply inverse of pivotMatrix
  15781. if (this._postMultiplyPivotMatrix) {
  15782. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15783. }
  15784. // Normal matrix
  15785. if (this.scaling.isNonUniform) {
  15786. this._updateNonUniformScalingState(true);
  15787. }
  15788. else if (this.parent && this.parent._nonUniformScaling) {
  15789. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15790. }
  15791. else {
  15792. this._updateNonUniformScalingState(false);
  15793. }
  15794. this._afterComputeWorldMatrix();
  15795. // Absolute position
  15796. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15797. // Callbacks
  15798. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15799. if (!this._poseMatrix) {
  15800. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15801. }
  15802. // Cache the determinant
  15803. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15804. return this._worldMatrix;
  15805. };
  15806. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15807. };
  15808. /**
  15809. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15810. * @param func: callback function to add
  15811. *
  15812. * Returns the TransformNode.
  15813. */
  15814. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15815. this.onAfterWorldMatrixUpdateObservable.add(func);
  15816. return this;
  15817. };
  15818. /**
  15819. * Removes a registered callback function.
  15820. * Returns the TransformNode.
  15821. */
  15822. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15823. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15824. return this;
  15825. };
  15826. /**
  15827. * Clone the current transform node
  15828. * Returns the new transform node
  15829. * @param name Name of the new clone
  15830. * @param newParent New parent for the clone
  15831. * @param doNotCloneChildren Do not clone children hierarchy
  15832. */
  15833. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15834. var _this = this;
  15835. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15836. result.name = name;
  15837. result.id = name;
  15838. if (newParent) {
  15839. result.parent = newParent;
  15840. }
  15841. if (!doNotCloneChildren) {
  15842. // Children
  15843. var directDescendants = this.getDescendants(true);
  15844. for (var index = 0; index < directDescendants.length; index++) {
  15845. var child = directDescendants[index];
  15846. if (child.clone) {
  15847. child.clone(name + "." + child.name, result);
  15848. }
  15849. }
  15850. }
  15851. return result;
  15852. };
  15853. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15854. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15855. serializationObject.type = this.getClassName();
  15856. // Parent
  15857. if (this.parent) {
  15858. serializationObject.parentId = this.parent.id;
  15859. }
  15860. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15861. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15862. }
  15863. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15864. serializationObject.isEnabled = this.isEnabled();
  15865. // Parent
  15866. if (this.parent) {
  15867. serializationObject.parentId = this.parent.id;
  15868. }
  15869. return serializationObject;
  15870. };
  15871. // Statics
  15872. /**
  15873. * Returns a new TransformNode object parsed from the source provided.
  15874. * The parameter `parsedMesh` is the source.
  15875. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15876. */
  15877. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15878. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15879. if (BABYLON.Tags) {
  15880. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15881. }
  15882. if (parsedTransformNode.localMatrix) {
  15883. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15884. }
  15885. else if (parsedTransformNode.pivotMatrix) {
  15886. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15887. }
  15888. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15889. // Parent
  15890. if (parsedTransformNode.parentId) {
  15891. transformNode._waitingParentId = parsedTransformNode.parentId;
  15892. }
  15893. return transformNode;
  15894. };
  15895. /**
  15896. * Disposes the TransformNode.
  15897. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15898. * Returns nothing.
  15899. */
  15900. TransformNode.prototype.dispose = function (doNotRecurse) {
  15901. // Animations
  15902. this.getScene().stopAnimation(this);
  15903. // Remove from scene
  15904. this.getScene().removeTransformNode(this);
  15905. if (!doNotRecurse) {
  15906. // Children
  15907. var objects = this.getDescendants(true);
  15908. for (var index = 0; index < objects.length; index++) {
  15909. objects[index].dispose();
  15910. }
  15911. }
  15912. else {
  15913. var childMeshes = this.getChildMeshes(true);
  15914. for (index = 0; index < childMeshes.length; index++) {
  15915. var child = childMeshes[index];
  15916. child.parent = null;
  15917. child.computeWorldMatrix(true);
  15918. }
  15919. }
  15920. this.onAfterWorldMatrixUpdateObservable.clear();
  15921. _super.prototype.dispose.call(this);
  15922. };
  15923. // Statics
  15924. TransformNode.BILLBOARDMODE_NONE = 0;
  15925. TransformNode.BILLBOARDMODE_X = 1;
  15926. TransformNode.BILLBOARDMODE_Y = 2;
  15927. TransformNode.BILLBOARDMODE_Z = 4;
  15928. TransformNode.BILLBOARDMODE_ALL = 7;
  15929. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15930. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15931. __decorate([
  15932. BABYLON.serializeAsVector3()
  15933. ], TransformNode.prototype, "_rotation", void 0);
  15934. __decorate([
  15935. BABYLON.serializeAsQuaternion()
  15936. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15937. __decorate([
  15938. BABYLON.serializeAsVector3()
  15939. ], TransformNode.prototype, "_scaling", void 0);
  15940. __decorate([
  15941. BABYLON.serialize()
  15942. ], TransformNode.prototype, "billboardMode", void 0);
  15943. __decorate([
  15944. BABYLON.serialize()
  15945. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15946. __decorate([
  15947. BABYLON.serialize()
  15948. ], TransformNode.prototype, "infiniteDistance", void 0);
  15949. __decorate([
  15950. BABYLON.serializeAsVector3()
  15951. ], TransformNode.prototype, "position", void 0);
  15952. return TransformNode;
  15953. }(BABYLON.Node));
  15954. BABYLON.TransformNode = TransformNode;
  15955. })(BABYLON || (BABYLON = {}));
  15956. //# sourceMappingURL=babylon.transformNode.js.map
  15957. var BABYLON;
  15958. (function (BABYLON) {
  15959. var AbstractMesh = /** @class */ (function (_super) {
  15960. __extends(AbstractMesh, _super);
  15961. // Constructor
  15962. function AbstractMesh(name, scene) {
  15963. if (scene === void 0) { scene = null; }
  15964. var _this = _super.call(this, name, scene, false) || this;
  15965. _this._facetNb = 0; // facet number
  15966. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15967. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15968. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15969. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15970. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15971. _this._subDiv = {
  15972. max: 1,
  15973. X: 1,
  15974. Y: 1,
  15975. Z: 1
  15976. };
  15977. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15978. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15979. // Events
  15980. /**
  15981. * An event triggered when this mesh collides with another one
  15982. * @type {BABYLON.Observable}
  15983. */
  15984. _this.onCollideObservable = new BABYLON.Observable();
  15985. /**
  15986. * An event triggered when the collision's position changes
  15987. * @type {BABYLON.Observable}
  15988. */
  15989. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15990. /**
  15991. * An event triggered when material is changed
  15992. * @type {BABYLON.Observable}
  15993. */
  15994. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15995. // Properties
  15996. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15997. /**
  15998. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15999. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16000. * or
  16001. * 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.
  16002. * for more info check WebGl documentations
  16003. */
  16004. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16005. /**
  16006. * 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:
  16007. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16008. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16009. * 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.
  16010. */
  16011. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16012. /**
  16013. * 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.
  16014. * The default value is -1 which means don't break the query and wait till the result.
  16015. */
  16016. _this.occlusionRetryCount = -1;
  16017. _this._occlusionInternalRetryCounter = 0;
  16018. _this._isOccluded = false;
  16019. _this._isOcclusionQueryInProgress = false;
  16020. _this._visibility = 1.0;
  16021. _this.alphaIndex = Number.MAX_VALUE;
  16022. _this.isVisible = true;
  16023. _this.isPickable = true;
  16024. _this.showBoundingBox = false;
  16025. _this.showSubMeshesBoundingBox = false;
  16026. _this.isBlocker = false;
  16027. _this.enablePointerMoveEvents = false;
  16028. _this.renderingGroupId = 0;
  16029. _this._receiveShadows = false;
  16030. _this.renderOutline = false;
  16031. _this.outlineColor = BABYLON.Color3.Red();
  16032. _this.outlineWidth = 0.02;
  16033. _this.renderOverlay = false;
  16034. _this.overlayColor = BABYLON.Color3.Red();
  16035. _this.overlayAlpha = 0.5;
  16036. _this._hasVertexAlpha = false;
  16037. _this._useVertexColors = true;
  16038. _this._computeBonesUsingShaders = true;
  16039. _this._numBoneInfluencers = 4;
  16040. _this._applyFog = true;
  16041. _this.useOctreeForRenderingSelection = true;
  16042. _this.useOctreeForPicking = true;
  16043. _this.useOctreeForCollisions = true;
  16044. _this._layerMask = 0x0FFFFFFF;
  16045. /**
  16046. * True if the mesh must be rendered in any case.
  16047. */
  16048. _this.alwaysSelectAsActiveMesh = false;
  16049. /**
  16050. * This scene's action manager
  16051. * @type {BABYLON.ActionManager}
  16052. */
  16053. _this.actionManager = null;
  16054. // Physics
  16055. _this.physicsImpostor = null;
  16056. // Collisions
  16057. _this._checkCollisions = false;
  16058. _this._collisionMask = -1;
  16059. _this._collisionGroup = -1;
  16060. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16061. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16062. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16063. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16064. // Edges
  16065. _this.edgesWidth = 1;
  16066. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16067. // Cache
  16068. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16069. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16070. _this._isDisposed = false;
  16071. _this._renderId = 0;
  16072. _this._intersectionsInProgress = new Array();
  16073. _this._unIndexed = false;
  16074. _this._lightSources = new Array();
  16075. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16076. if (collidedMesh === void 0) { collidedMesh = null; }
  16077. //TODO move this to the collision coordinator!
  16078. if (_this.getScene().workerCollisions)
  16079. newPosition.multiplyInPlace(_this._collider._radius);
  16080. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16081. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16082. _this.position.addInPlace(_this._diffPositionForCollisions);
  16083. }
  16084. if (collidedMesh) {
  16085. _this.onCollideObservable.notifyObservers(collidedMesh);
  16086. }
  16087. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16088. };
  16089. _this.getScene().addMesh(_this);
  16090. _this._resyncLightSources();
  16091. return _this;
  16092. }
  16093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16094. get: function () {
  16095. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16101. get: function () {
  16102. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16108. get: function () {
  16109. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16110. },
  16111. enumerable: true,
  16112. configurable: true
  16113. });
  16114. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16115. get: function () {
  16116. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16117. },
  16118. enumerable: true,
  16119. configurable: true
  16120. });
  16121. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16122. get: function () {
  16123. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16124. },
  16125. enumerable: true,
  16126. configurable: true
  16127. });
  16128. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16129. /**
  16130. * Read-only : the number of facets in the mesh
  16131. */
  16132. get: function () {
  16133. return this._facetNb;
  16134. },
  16135. enumerable: true,
  16136. configurable: true
  16137. });
  16138. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16139. /**
  16140. * The number (integer) of subdivisions per axis in the partioning space
  16141. */
  16142. get: function () {
  16143. return this._partitioningSubdivisions;
  16144. },
  16145. set: function (nb) {
  16146. this._partitioningSubdivisions = nb;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16152. /**
  16153. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16154. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16155. */
  16156. get: function () {
  16157. return this._partitioningBBoxRatio;
  16158. },
  16159. set: function (ratio) {
  16160. this._partitioningBBoxRatio = ratio;
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16166. /**
  16167. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16168. * Works only for updatable meshes.
  16169. * Doesn't work with multi-materials.
  16170. */
  16171. get: function () {
  16172. return this._facetDepthSort;
  16173. },
  16174. set: function (sort) {
  16175. this._facetDepthSort = sort;
  16176. },
  16177. enumerable: true,
  16178. configurable: true
  16179. });
  16180. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16181. /**
  16182. * The location (Vector3) where the facet depth sort must be computed from.
  16183. * By default, the active camera position.
  16184. * Used only when facet depth sort is enabled.
  16185. */
  16186. get: function () {
  16187. return this._facetDepthSortFrom;
  16188. },
  16189. set: function (location) {
  16190. this._facetDepthSortFrom = location;
  16191. },
  16192. enumerable: true,
  16193. configurable: true
  16194. });
  16195. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16196. /**
  16197. * Read-only boolean : is the feature facetData enabled ?
  16198. */
  16199. get: function () {
  16200. return this._facetDataEnabled;
  16201. },
  16202. enumerable: true,
  16203. configurable: true
  16204. });
  16205. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16206. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16207. return false;
  16208. }
  16209. this._markSubMeshesAsMiscDirty();
  16210. return true;
  16211. };
  16212. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16213. set: function (callback) {
  16214. if (this._onCollideObserver) {
  16215. this.onCollideObservable.remove(this._onCollideObserver);
  16216. }
  16217. this._onCollideObserver = this.onCollideObservable.add(callback);
  16218. },
  16219. enumerable: true,
  16220. configurable: true
  16221. });
  16222. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16223. set: function (callback) {
  16224. if (this._onCollisionPositionChangeObserver) {
  16225. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16226. }
  16227. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16228. },
  16229. enumerable: true,
  16230. configurable: true
  16231. });
  16232. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16233. /**
  16234. * 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.
  16235. */
  16236. get: function () {
  16237. return this._isOccluded;
  16238. },
  16239. set: function (value) {
  16240. this._isOccluded = value;
  16241. },
  16242. enumerable: true,
  16243. configurable: true
  16244. });
  16245. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16246. /**
  16247. * Flag to check the progress status of the query
  16248. */
  16249. get: function () {
  16250. return this._isOcclusionQueryInProgress;
  16251. },
  16252. enumerable: true,
  16253. configurable: true
  16254. });
  16255. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16256. /**
  16257. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16258. */
  16259. get: function () {
  16260. return this._visibility;
  16261. },
  16262. /**
  16263. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16264. */
  16265. set: function (value) {
  16266. if (this._visibility === value) {
  16267. return;
  16268. }
  16269. this._visibility = value;
  16270. this._markSubMeshesAsMiscDirty();
  16271. },
  16272. enumerable: true,
  16273. configurable: true
  16274. });
  16275. Object.defineProperty(AbstractMesh.prototype, "material", {
  16276. get: function () {
  16277. return this._material;
  16278. },
  16279. set: function (value) {
  16280. if (this._material === value) {
  16281. return;
  16282. }
  16283. this._material = value;
  16284. if (this.onMaterialChangedObservable.hasObservers) {
  16285. this.onMaterialChangedObservable.notifyObservers(this);
  16286. }
  16287. if (!this.subMeshes) {
  16288. return;
  16289. }
  16290. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16291. var subMesh = _a[_i];
  16292. subMesh.setEffect(null);
  16293. }
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16299. get: function () {
  16300. return this._receiveShadows;
  16301. },
  16302. set: function (value) {
  16303. if (this._receiveShadows === value) {
  16304. return;
  16305. }
  16306. this._receiveShadows = value;
  16307. this._markSubMeshesAsLightDirty();
  16308. },
  16309. enumerable: true,
  16310. configurable: true
  16311. });
  16312. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16313. get: function () {
  16314. return this._hasVertexAlpha;
  16315. },
  16316. set: function (value) {
  16317. if (this._hasVertexAlpha === value) {
  16318. return;
  16319. }
  16320. this._hasVertexAlpha = value;
  16321. this._markSubMeshesAsAttributesDirty();
  16322. this._markSubMeshesAsMiscDirty();
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16328. get: function () {
  16329. return this._useVertexColors;
  16330. },
  16331. set: function (value) {
  16332. if (this._useVertexColors === value) {
  16333. return;
  16334. }
  16335. this._useVertexColors = value;
  16336. this._markSubMeshesAsAttributesDirty();
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16342. get: function () {
  16343. return this._computeBonesUsingShaders;
  16344. },
  16345. set: function (value) {
  16346. if (this._computeBonesUsingShaders === value) {
  16347. return;
  16348. }
  16349. this._computeBonesUsingShaders = value;
  16350. this._markSubMeshesAsAttributesDirty();
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16356. get: function () {
  16357. return this._numBoneInfluencers;
  16358. },
  16359. set: function (value) {
  16360. if (this._numBoneInfluencers === value) {
  16361. return;
  16362. }
  16363. this._numBoneInfluencers = value;
  16364. this._markSubMeshesAsAttributesDirty();
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16370. get: function () {
  16371. return this._applyFog;
  16372. },
  16373. set: function (value) {
  16374. if (this._applyFog === value) {
  16375. return;
  16376. }
  16377. this._applyFog = value;
  16378. this._markSubMeshesAsMiscDirty();
  16379. },
  16380. enumerable: true,
  16381. configurable: true
  16382. });
  16383. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16384. get: function () {
  16385. return this._layerMask;
  16386. },
  16387. set: function (value) {
  16388. if (value === this._layerMask) {
  16389. return;
  16390. }
  16391. this._layerMask = value;
  16392. this._resyncLightSources();
  16393. },
  16394. enumerable: true,
  16395. configurable: true
  16396. });
  16397. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16398. get: function () {
  16399. return this._collisionMask;
  16400. },
  16401. set: function (mask) {
  16402. this._collisionMask = !isNaN(mask) ? mask : -1;
  16403. },
  16404. enumerable: true,
  16405. configurable: true
  16406. });
  16407. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16408. get: function () {
  16409. return this._collisionGroup;
  16410. },
  16411. set: function (mask) {
  16412. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16413. },
  16414. enumerable: true,
  16415. configurable: true
  16416. });
  16417. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16418. get: function () {
  16419. return null;
  16420. },
  16421. enumerable: true,
  16422. configurable: true
  16423. });
  16424. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16425. get: function () {
  16426. return this._skeleton;
  16427. },
  16428. set: function (value) {
  16429. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16430. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16431. }
  16432. if (value && value.needInitialSkinMatrix) {
  16433. value._registerMeshWithPoseMatrix(this);
  16434. }
  16435. this._skeleton = value;
  16436. if (!this._skeleton) {
  16437. this._bonesTransformMatrices = null;
  16438. }
  16439. this._markSubMeshesAsAttributesDirty();
  16440. },
  16441. enumerable: true,
  16442. configurable: true
  16443. });
  16444. /**
  16445. * Boolean : true if the mesh has been disposed.
  16446. */
  16447. AbstractMesh.prototype.isDisposed = function () {
  16448. return this._isDisposed;
  16449. };
  16450. /**
  16451. * Returns the string "AbstractMesh"
  16452. */
  16453. AbstractMesh.prototype.getClassName = function () {
  16454. return "AbstractMesh";
  16455. };
  16456. /**
  16457. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16458. */
  16459. AbstractMesh.prototype.toString = function (fullDetails) {
  16460. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16461. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16462. if (this._skeleton) {
  16463. ret += ", skeleton: " + this._skeleton.name;
  16464. }
  16465. if (fullDetails) {
  16466. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16467. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16468. }
  16469. return ret;
  16470. };
  16471. AbstractMesh.prototype._rebuild = function () {
  16472. if (this._occlusionQuery) {
  16473. this._occlusionQuery = null;
  16474. }
  16475. if (this._edgesRenderer) {
  16476. this._edgesRenderer._rebuild();
  16477. }
  16478. if (!this.subMeshes) {
  16479. return;
  16480. }
  16481. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16482. var subMesh = _a[_i];
  16483. subMesh._rebuild();
  16484. }
  16485. };
  16486. AbstractMesh.prototype._resyncLightSources = function () {
  16487. this._lightSources.length = 0;
  16488. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16489. var light = _a[_i];
  16490. if (!light.isEnabled()) {
  16491. continue;
  16492. }
  16493. if (light.canAffectMesh(this)) {
  16494. this._lightSources.push(light);
  16495. }
  16496. }
  16497. this._markSubMeshesAsLightDirty();
  16498. };
  16499. AbstractMesh.prototype._resyncLighSource = function (light) {
  16500. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16501. var index = this._lightSources.indexOf(light);
  16502. if (index === -1) {
  16503. if (!isIn) {
  16504. return;
  16505. }
  16506. this._lightSources.push(light);
  16507. }
  16508. else {
  16509. if (isIn) {
  16510. return;
  16511. }
  16512. this._lightSources.splice(index, 1);
  16513. }
  16514. this._markSubMeshesAsLightDirty();
  16515. };
  16516. AbstractMesh.prototype._removeLightSource = function (light) {
  16517. var index = this._lightSources.indexOf(light);
  16518. if (index === -1) {
  16519. return;
  16520. }
  16521. this._lightSources.splice(index, 1);
  16522. this._markSubMeshesAsLightDirty();
  16523. };
  16524. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16525. if (!this.subMeshes) {
  16526. return;
  16527. }
  16528. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16529. var subMesh = _a[_i];
  16530. if (subMesh._materialDefines) {
  16531. func(subMesh._materialDefines);
  16532. }
  16533. }
  16534. };
  16535. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16536. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16537. };
  16538. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16539. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16540. };
  16541. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16542. if (!this.subMeshes) {
  16543. return;
  16544. }
  16545. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16546. var subMesh = _a[_i];
  16547. var material = subMesh.getMaterial();
  16548. if (material) {
  16549. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16550. }
  16551. }
  16552. };
  16553. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16554. /**
  16555. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16556. * Default : (1.0, 1.0, 1.0)
  16557. */
  16558. get: function () {
  16559. return this._scaling;
  16560. },
  16561. /**
  16562. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16563. * Default : (1.0, 1.0, 1.0)
  16564. */
  16565. set: function (newScaling) {
  16566. this._scaling = newScaling;
  16567. if (this.physicsImpostor) {
  16568. this.physicsImpostor.forceUpdate();
  16569. }
  16570. },
  16571. enumerable: true,
  16572. configurable: true
  16573. });
  16574. // Methods
  16575. /**
  16576. * Disables the mesh edger rendering mode.
  16577. * Returns the AbstractMesh.
  16578. */
  16579. AbstractMesh.prototype.disableEdgesRendering = function () {
  16580. if (this._edgesRenderer) {
  16581. this._edgesRenderer.dispose();
  16582. this._edgesRenderer = null;
  16583. }
  16584. return this;
  16585. };
  16586. /**
  16587. * Enables the edge rendering mode on the mesh.
  16588. * This mode makes the mesh edges visible.
  16589. * Returns the AbstractMesh.
  16590. */
  16591. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16592. if (epsilon === void 0) { epsilon = 0.95; }
  16593. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16594. this.disableEdgesRendering();
  16595. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16596. return this;
  16597. };
  16598. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16599. /**
  16600. * Returns true if the mesh is blocked. Used by the class Mesh.
  16601. * Returns the boolean `false` by default.
  16602. */
  16603. get: function () {
  16604. return false;
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. /**
  16610. * Returns the mesh itself by default, used by the class Mesh.
  16611. * Returned type : AbstractMesh
  16612. */
  16613. AbstractMesh.prototype.getLOD = function (camera) {
  16614. return this;
  16615. };
  16616. /**
  16617. * Returns 0 by default, used by the class Mesh.
  16618. * Returns an integer.
  16619. */
  16620. AbstractMesh.prototype.getTotalVertices = function () {
  16621. return 0;
  16622. };
  16623. /**
  16624. * Returns null by default, used by the class Mesh.
  16625. * Returned type : integer array
  16626. */
  16627. AbstractMesh.prototype.getIndices = function () {
  16628. return null;
  16629. };
  16630. /**
  16631. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16632. * Returned type : float array or Float32Array
  16633. */
  16634. AbstractMesh.prototype.getVerticesData = function (kind) {
  16635. return null;
  16636. };
  16637. /**
  16638. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16639. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16640. * The `data` are either a numeric array either a Float32Array.
  16641. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16642. * 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).
  16643. * Note that a new underlying VertexBuffer object is created each call.
  16644. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16645. *
  16646. * Possible `kind` values :
  16647. * - BABYLON.VertexBuffer.PositionKind
  16648. * - BABYLON.VertexBuffer.UVKind
  16649. * - BABYLON.VertexBuffer.UV2Kind
  16650. * - BABYLON.VertexBuffer.UV3Kind
  16651. * - BABYLON.VertexBuffer.UV4Kind
  16652. * - BABYLON.VertexBuffer.UV5Kind
  16653. * - BABYLON.VertexBuffer.UV6Kind
  16654. * - BABYLON.VertexBuffer.ColorKind
  16655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16659. *
  16660. * Returns the Mesh.
  16661. */
  16662. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16663. return this;
  16664. };
  16665. /**
  16666. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16667. * If the mesh has no geometry, it is simply returned as it is.
  16668. * The `data` are either a numeric array either a Float32Array.
  16669. * No new underlying VertexBuffer object is created.
  16670. * 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.
  16671. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16672. *
  16673. * Possible `kind` values :
  16674. * - BABYLON.VertexBuffer.PositionKind
  16675. * - BABYLON.VertexBuffer.UVKind
  16676. * - BABYLON.VertexBuffer.UV2Kind
  16677. * - BABYLON.VertexBuffer.UV3Kind
  16678. * - BABYLON.VertexBuffer.UV4Kind
  16679. * - BABYLON.VertexBuffer.UV5Kind
  16680. * - BABYLON.VertexBuffer.UV6Kind
  16681. * - BABYLON.VertexBuffer.ColorKind
  16682. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16683. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16684. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16685. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16686. *
  16687. * Returns the Mesh.
  16688. */
  16689. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16690. return this;
  16691. };
  16692. /**
  16693. * Sets the mesh indices.
  16694. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16695. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16696. * This method creates a new index buffer each call.
  16697. * Returns the Mesh.
  16698. */
  16699. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16700. return this;
  16701. };
  16702. /** Returns false by default, used by the class Mesh.
  16703. * Returns a boolean
  16704. */
  16705. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16706. return false;
  16707. };
  16708. /**
  16709. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16710. * Returns a BoundingInfo
  16711. */
  16712. AbstractMesh.prototype.getBoundingInfo = function () {
  16713. if (this._masterMesh) {
  16714. return this._masterMesh.getBoundingInfo();
  16715. }
  16716. if (!this._boundingInfo) {
  16717. // this._boundingInfo is being created here
  16718. this._updateBoundingInfo();
  16719. }
  16720. // cannot be null.
  16721. return this._boundingInfo;
  16722. };
  16723. /**
  16724. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16725. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16726. */
  16727. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16728. if (includeDescendants === void 0) { includeDescendants = true; }
  16729. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16730. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16731. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16732. if (maxDimension === 0) {
  16733. return this;
  16734. }
  16735. var scale = 1 / maxDimension;
  16736. this.scaling.scaleInPlace(scale);
  16737. return this;
  16738. };
  16739. /**
  16740. * Sets a mesh new object BoundingInfo.
  16741. * Returns the AbstractMesh.
  16742. */
  16743. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16744. this._boundingInfo = boundingInfo;
  16745. return this;
  16746. };
  16747. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16748. get: function () {
  16749. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. AbstractMesh.prototype._preActivate = function () {
  16755. };
  16756. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16757. };
  16758. AbstractMesh.prototype._activate = function (renderId) {
  16759. this._renderId = renderId;
  16760. };
  16761. /**
  16762. * Returns the latest update of the World matrix
  16763. * Returns a Matrix.
  16764. */
  16765. AbstractMesh.prototype.getWorldMatrix = function () {
  16766. if (this._masterMesh) {
  16767. return this._masterMesh.getWorldMatrix();
  16768. }
  16769. return _super.prototype.getWorldMatrix.call(this);
  16770. };
  16771. /**
  16772. * Returns the latest update of the World matrix determinant.
  16773. */
  16774. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16775. if (this._masterMesh) {
  16776. return this._masterMesh._getWorldMatrixDeterminant();
  16777. }
  16778. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16779. };
  16780. // ================================== Point of View Movement =================================
  16781. /**
  16782. * Perform relative position change from the point of view of behind the front of the mesh.
  16783. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16784. * Supports definition of mesh facing forward or backward.
  16785. * @param {number} amountRight
  16786. * @param {number} amountUp
  16787. * @param {number} amountForward
  16788. *
  16789. * Returns the AbstractMesh.
  16790. */
  16791. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16792. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16793. return this;
  16794. };
  16795. /**
  16796. * Calculate relative position change from the point of view of behind the front of the mesh.
  16797. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16798. * Supports definition of mesh facing forward or backward.
  16799. * @param {number} amountRight
  16800. * @param {number} amountUp
  16801. * @param {number} amountForward
  16802. *
  16803. * Returns a new Vector3.
  16804. */
  16805. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16806. var rotMatrix = new BABYLON.Matrix();
  16807. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16808. rotQuaternion.toRotationMatrix(rotMatrix);
  16809. var translationDelta = BABYLON.Vector3.Zero();
  16810. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16811. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16812. return translationDelta;
  16813. };
  16814. // ================================== Point of View Rotation =================================
  16815. /**
  16816. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16817. * Supports definition of mesh facing forward or backward.
  16818. * @param {number} flipBack
  16819. * @param {number} twirlClockwise
  16820. * @param {number} tiltRight
  16821. *
  16822. * Returns the AbstractMesh.
  16823. */
  16824. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16825. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16826. return this;
  16827. };
  16828. /**
  16829. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16830. * Supports definition of mesh facing forward or backward.
  16831. * @param {number} flipBack
  16832. * @param {number} twirlClockwise
  16833. * @param {number} tiltRight
  16834. *
  16835. * Returns a new Vector3.
  16836. */
  16837. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16838. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16839. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16840. };
  16841. /**
  16842. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16843. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16844. */
  16845. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16846. if (includeDescendants === void 0) { includeDescendants = true; }
  16847. this.computeWorldMatrix(true);
  16848. var min;
  16849. var max;
  16850. var boundingInfo = this.getBoundingInfo();
  16851. if (!this.subMeshes) {
  16852. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16853. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16854. }
  16855. else {
  16856. min = boundingInfo.boundingBox.minimumWorld;
  16857. max = boundingInfo.boundingBox.maximumWorld;
  16858. }
  16859. if (includeDescendants) {
  16860. var descendants = this.getDescendants(false);
  16861. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16862. var descendant = descendants_1[_i];
  16863. var childMesh = descendant;
  16864. childMesh.computeWorldMatrix(true);
  16865. //make sure we have the needed params to get mix and max
  16866. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16867. continue;
  16868. }
  16869. var childBoundingInfo = childMesh.getBoundingInfo();
  16870. var boundingBox = childBoundingInfo.boundingBox;
  16871. var minBox = boundingBox.minimumWorld;
  16872. var maxBox = boundingBox.maximumWorld;
  16873. BABYLON.Tools.CheckExtends(minBox, min, max);
  16874. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16875. }
  16876. }
  16877. return {
  16878. min: min,
  16879. max: max
  16880. };
  16881. };
  16882. /**
  16883. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16884. * Returns the AbstractMesh.
  16885. */
  16886. AbstractMesh.prototype._updateBoundingInfo = function () {
  16887. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16888. this._boundingInfo.update(this.worldMatrixFromCache);
  16889. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16890. return this;
  16891. };
  16892. /**
  16893. * Update a mesh's children BoundingInfo objects only.
  16894. * Returns the AbstractMesh.
  16895. */
  16896. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16897. if (!this.subMeshes) {
  16898. return this;
  16899. }
  16900. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16901. var subMesh = this.subMeshes[subIndex];
  16902. if (!subMesh.IsGlobal) {
  16903. subMesh.updateBoundingInfo(matrix);
  16904. }
  16905. }
  16906. return this;
  16907. };
  16908. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16909. // Bounding info
  16910. this._updateBoundingInfo();
  16911. };
  16912. /**
  16913. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16914. * A mesh is in the frustum if its bounding box intersects the frustum.
  16915. * Boolean returned.
  16916. */
  16917. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16918. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16919. };
  16920. /**
  16921. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16922. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16923. * Boolean returned.
  16924. */
  16925. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16926. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16927. ;
  16928. };
  16929. /**
  16930. * True if the mesh intersects another mesh or a SolidParticle object.
  16931. * 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)
  16932. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16933. * Returns a boolean.
  16934. */
  16935. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16936. if (precise === void 0) { precise = false; }
  16937. if (!this._boundingInfo || !mesh._boundingInfo) {
  16938. return false;
  16939. }
  16940. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16941. return true;
  16942. }
  16943. if (includeDescendants) {
  16944. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16945. var child = _a[_i];
  16946. if (child.intersectsMesh(mesh, precise, true)) {
  16947. return true;
  16948. }
  16949. }
  16950. }
  16951. return false;
  16952. };
  16953. /**
  16954. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16955. * Returns a boolean.
  16956. */
  16957. AbstractMesh.prototype.intersectsPoint = function (point) {
  16958. if (!this._boundingInfo) {
  16959. return false;
  16960. }
  16961. return this._boundingInfo.intersectsPoint(point);
  16962. };
  16963. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16964. return this.physicsImpostor;
  16965. };
  16966. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16967. if (camera === void 0) { camera = null; }
  16968. if (!camera) {
  16969. camera = this.getScene().activeCamera;
  16970. }
  16971. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16972. };
  16973. /**
  16974. * Returns the distance from the mesh to the active camera.
  16975. * Returns a float.
  16976. */
  16977. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16978. if (camera === void 0) { camera = null; }
  16979. if (!camera) {
  16980. camera = this.getScene().activeCamera;
  16981. }
  16982. return this.absolutePosition.subtract(camera.position).length();
  16983. };
  16984. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16985. if (!this.physicsImpostor) {
  16986. return this;
  16987. }
  16988. this.physicsImpostor.applyImpulse(force, contactPoint);
  16989. return this;
  16990. };
  16991. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16992. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16993. return this;
  16994. }
  16995. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16996. mainPivot: pivot1,
  16997. connectedPivot: pivot2,
  16998. nativeParams: options
  16999. });
  17000. return this;
  17001. };
  17002. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17003. // Collisions
  17004. /**
  17005. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17006. * Default `false`.
  17007. */
  17008. get: function () {
  17009. return this._checkCollisions;
  17010. },
  17011. set: function (collisionEnabled) {
  17012. this._checkCollisions = collisionEnabled;
  17013. if (this.getScene().workerCollisions) {
  17014. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17015. }
  17016. },
  17017. enumerable: true,
  17018. configurable: true
  17019. });
  17020. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17021. /**
  17022. * Gets Collider object used to compute collisions (not physics)
  17023. */
  17024. get: function () {
  17025. return this._collider;
  17026. },
  17027. enumerable: true,
  17028. configurable: true
  17029. });
  17030. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17031. var globalPosition = this.getAbsolutePosition();
  17032. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17033. if (!this._collider) {
  17034. this._collider = new BABYLON.Collider();
  17035. }
  17036. this._collider._radius = this.ellipsoid;
  17037. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17038. return this;
  17039. };
  17040. // Submeshes octree
  17041. /**
  17042. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17043. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17044. * Returns an Octree of submeshes.
  17045. */
  17046. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17047. if (maxCapacity === void 0) { maxCapacity = 64; }
  17048. if (maxDepth === void 0) { maxDepth = 2; }
  17049. if (!this._submeshesOctree) {
  17050. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17051. }
  17052. this.computeWorldMatrix(true);
  17053. var boundingInfo = this.getBoundingInfo();
  17054. // Update octree
  17055. var bbox = boundingInfo.boundingBox;
  17056. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17057. return this._submeshesOctree;
  17058. };
  17059. // Collisions
  17060. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17061. this._generatePointsArray();
  17062. if (!this._positions) {
  17063. return this;
  17064. }
  17065. // Transformation
  17066. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17067. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17068. subMesh._lastColliderWorldVertices = [];
  17069. subMesh._trianglePlanes = [];
  17070. var start = subMesh.verticesStart;
  17071. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17072. for (var i = start; i < end; i++) {
  17073. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17074. }
  17075. }
  17076. // Collide
  17077. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17078. if (collider.collisionFound) {
  17079. collider.collidedMesh = this;
  17080. }
  17081. return this;
  17082. };
  17083. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17084. var subMeshes;
  17085. var len;
  17086. // Octrees
  17087. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17088. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17089. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17090. len = intersections.length;
  17091. subMeshes = intersections.data;
  17092. }
  17093. else {
  17094. subMeshes = this.subMeshes;
  17095. len = subMeshes.length;
  17096. }
  17097. for (var index = 0; index < len; index++) {
  17098. var subMesh = subMeshes[index];
  17099. // Bounding test
  17100. if (len > 1 && !subMesh._checkCollision(collider))
  17101. continue;
  17102. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17103. }
  17104. return this;
  17105. };
  17106. AbstractMesh.prototype._checkCollision = function (collider) {
  17107. // Bounding box test
  17108. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17109. return this;
  17110. // Transformation matrix
  17111. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17112. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17113. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17114. return this;
  17115. };
  17116. // Picking
  17117. AbstractMesh.prototype._generatePointsArray = function () {
  17118. return false;
  17119. };
  17120. /**
  17121. * Checks if the passed Ray intersects with the mesh.
  17122. * Returns an object PickingInfo.
  17123. */
  17124. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17125. var pickingInfo = new BABYLON.PickingInfo();
  17126. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17127. return pickingInfo;
  17128. }
  17129. if (!this._generatePointsArray()) {
  17130. return pickingInfo;
  17131. }
  17132. var intersectInfo = null;
  17133. // Octrees
  17134. var subMeshes;
  17135. var len;
  17136. if (this._submeshesOctree && this.useOctreeForPicking) {
  17137. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17138. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17139. len = intersections.length;
  17140. subMeshes = intersections.data;
  17141. }
  17142. else {
  17143. subMeshes = this.subMeshes;
  17144. len = subMeshes.length;
  17145. }
  17146. for (var index = 0; index < len; index++) {
  17147. var subMesh = subMeshes[index];
  17148. // Bounding test
  17149. if (len > 1 && !subMesh.canIntersects(ray))
  17150. continue;
  17151. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17152. if (currentIntersectInfo) {
  17153. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17154. intersectInfo = currentIntersectInfo;
  17155. intersectInfo.subMeshId = index;
  17156. if (fastCheck) {
  17157. break;
  17158. }
  17159. }
  17160. }
  17161. }
  17162. if (intersectInfo) {
  17163. // Get picked point
  17164. var world = this.getWorldMatrix();
  17165. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17166. var direction = ray.direction.clone();
  17167. direction = direction.scale(intersectInfo.distance);
  17168. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17169. var pickedPoint = worldOrigin.add(worldDirection);
  17170. // Return result
  17171. pickingInfo.hit = true;
  17172. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17173. pickingInfo.pickedPoint = pickedPoint;
  17174. pickingInfo.pickedMesh = this;
  17175. pickingInfo.bu = intersectInfo.bu || 0;
  17176. pickingInfo.bv = intersectInfo.bv || 0;
  17177. pickingInfo.faceId = intersectInfo.faceId;
  17178. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17179. return pickingInfo;
  17180. }
  17181. return pickingInfo;
  17182. };
  17183. /**
  17184. * Clones the mesh, used by the class Mesh.
  17185. * Just returns `null` for an AbstractMesh.
  17186. */
  17187. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17188. return null;
  17189. };
  17190. /**
  17191. * Disposes all the mesh submeshes.
  17192. * Returns the AbstractMesh.
  17193. */
  17194. AbstractMesh.prototype.releaseSubMeshes = function () {
  17195. if (this.subMeshes) {
  17196. while (this.subMeshes.length) {
  17197. this.subMeshes[0].dispose();
  17198. }
  17199. }
  17200. else {
  17201. this.subMeshes = new Array();
  17202. }
  17203. return this;
  17204. };
  17205. /**
  17206. * Disposes the AbstractMesh.
  17207. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17208. * Returns nothing.
  17209. */
  17210. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17211. var _this = this;
  17212. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17213. var index;
  17214. // Action manager
  17215. if (this.actionManager !== undefined && this.actionManager !== null) {
  17216. this.actionManager.dispose();
  17217. this.actionManager = null;
  17218. }
  17219. // Skeleton
  17220. this.skeleton = null;
  17221. // Physics
  17222. if (this.physicsImpostor) {
  17223. this.physicsImpostor.dispose();
  17224. }
  17225. // Intersections in progress
  17226. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17227. var other = this._intersectionsInProgress[index];
  17228. var pos = other._intersectionsInProgress.indexOf(this);
  17229. other._intersectionsInProgress.splice(pos, 1);
  17230. }
  17231. this._intersectionsInProgress = [];
  17232. // Lights
  17233. var lights = this.getScene().lights;
  17234. lights.forEach(function (light) {
  17235. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17236. if (meshIndex !== -1) {
  17237. light.includedOnlyMeshes.splice(meshIndex, 1);
  17238. }
  17239. meshIndex = light.excludedMeshes.indexOf(_this);
  17240. if (meshIndex !== -1) {
  17241. light.excludedMeshes.splice(meshIndex, 1);
  17242. }
  17243. // Shadow generators
  17244. var generator = light.getShadowGenerator();
  17245. if (generator) {
  17246. var shadowMap = generator.getShadowMap();
  17247. if (shadowMap && shadowMap.renderList) {
  17248. meshIndex = shadowMap.renderList.indexOf(_this);
  17249. if (meshIndex !== -1) {
  17250. shadowMap.renderList.splice(meshIndex, 1);
  17251. }
  17252. }
  17253. }
  17254. });
  17255. // Edges
  17256. if (this._edgesRenderer) {
  17257. this._edgesRenderer.dispose();
  17258. this._edgesRenderer = null;
  17259. }
  17260. // SubMeshes
  17261. if (this.getClassName() !== "InstancedMesh") {
  17262. this.releaseSubMeshes();
  17263. }
  17264. // Octree
  17265. var sceneOctree = this.getScene().selectionOctree;
  17266. if (sceneOctree !== undefined && sceneOctree !== null) {
  17267. var index = sceneOctree.dynamicContent.indexOf(this);
  17268. if (index !== -1) {
  17269. sceneOctree.dynamicContent.splice(index, 1);
  17270. }
  17271. }
  17272. // Query
  17273. var engine = this.getScene().getEngine();
  17274. if (this._occlusionQuery) {
  17275. this._isOcclusionQueryInProgress = false;
  17276. engine.deleteQuery(this._occlusionQuery);
  17277. this._occlusionQuery = null;
  17278. }
  17279. // Engine
  17280. engine.wipeCaches();
  17281. // Remove from scene
  17282. this.getScene().removeMesh(this);
  17283. if (disposeMaterialAndTextures) {
  17284. if (this.material) {
  17285. this.material.dispose(false, true);
  17286. }
  17287. }
  17288. if (!doNotRecurse) {
  17289. // Particles
  17290. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17291. if (this.getScene().particleSystems[index].emitter === this) {
  17292. this.getScene().particleSystems[index].dispose();
  17293. index--;
  17294. }
  17295. }
  17296. }
  17297. // facet data
  17298. if (this._facetDataEnabled) {
  17299. this.disableFacetData();
  17300. }
  17301. this.onAfterWorldMatrixUpdateObservable.clear();
  17302. this.onCollideObservable.clear();
  17303. this.onCollisionPositionChangeObservable.clear();
  17304. this._isDisposed = true;
  17305. _super.prototype.dispose.call(this, doNotRecurse);
  17306. };
  17307. /**
  17308. * Adds the passed mesh as a child to the current mesh.
  17309. * Returns the AbstractMesh.
  17310. */
  17311. AbstractMesh.prototype.addChild = function (mesh) {
  17312. mesh.setParent(this);
  17313. return this;
  17314. };
  17315. /**
  17316. * Removes the passed mesh from the current mesh children list.
  17317. * Returns the AbstractMesh.
  17318. */
  17319. AbstractMesh.prototype.removeChild = function (mesh) {
  17320. mesh.setParent(null);
  17321. return this;
  17322. };
  17323. // Facet data
  17324. /**
  17325. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17326. * Returns the AbstractMesh.
  17327. */
  17328. AbstractMesh.prototype._initFacetData = function () {
  17329. if (!this._facetNormals) {
  17330. this._facetNormals = new Array();
  17331. }
  17332. if (!this._facetPositions) {
  17333. this._facetPositions = new Array();
  17334. }
  17335. if (!this._facetPartitioning) {
  17336. this._facetPartitioning = new Array();
  17337. }
  17338. this._facetNb = (this.getIndices().length / 3) | 0;
  17339. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17340. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17341. for (var f = 0; f < this._facetNb; f++) {
  17342. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17343. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17344. }
  17345. this._facetDataEnabled = true;
  17346. return this;
  17347. };
  17348. /**
  17349. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17350. * This method can be called within the render loop.
  17351. * 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.
  17352. * Returns the AbstractMesh.
  17353. */
  17354. AbstractMesh.prototype.updateFacetData = function () {
  17355. if (!this._facetDataEnabled) {
  17356. this._initFacetData();
  17357. }
  17358. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17359. var indices = this.getIndices();
  17360. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17361. var bInfo = this.getBoundingInfo();
  17362. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17363. // init arrays, matrix and sort function on first call
  17364. this._facetDepthSortEnabled = true;
  17365. if (indices instanceof Uint16Array) {
  17366. this._depthSortedIndices = new Uint16Array(indices);
  17367. }
  17368. else if (indices instanceof Uint32Array) {
  17369. this._depthSortedIndices = new Uint32Array(indices);
  17370. }
  17371. else {
  17372. var needs32bits = false;
  17373. for (var i = 0; i < indices.length; i++) {
  17374. if (indices[i] > 65535) {
  17375. needs32bits = true;
  17376. break;
  17377. }
  17378. }
  17379. if (needs32bits) {
  17380. this._depthSortedIndices = new Uint32Array(indices);
  17381. }
  17382. else {
  17383. this._depthSortedIndices = new Uint16Array(indices);
  17384. }
  17385. }
  17386. this._facetDepthSortFunction = function (f1, f2) {
  17387. return (f2.sqDistance - f1.sqDistance);
  17388. };
  17389. if (!this._facetDepthSortFrom) {
  17390. var camera = this.getScene().activeCamera;
  17391. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17392. }
  17393. this._depthSortedFacets = [];
  17394. for (var f = 0; f < this._facetNb; f++) {
  17395. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17396. this._depthSortedFacets.push(depthSortedFacet);
  17397. }
  17398. this._invertedMatrix = BABYLON.Matrix.Identity();
  17399. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17400. }
  17401. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17402. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17403. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17404. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17405. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17406. this._subDiv.max = this._partitioningSubdivisions;
  17407. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17408. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17409. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17410. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17411. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17412. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17413. // set the parameters for ComputeNormals()
  17414. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17415. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17416. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17417. this._facetParameters.bInfo = bInfo;
  17418. this._facetParameters.bbSize = this._bbSize;
  17419. this._facetParameters.subDiv = this._subDiv;
  17420. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17421. this._facetParameters.depthSort = this._facetDepthSort;
  17422. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17423. this.computeWorldMatrix(true);
  17424. this._worldMatrix.invertToRef(this._invertedMatrix);
  17425. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17426. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17427. }
  17428. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17429. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17430. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17431. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17432. var l = (this._depthSortedIndices.length / 3) | 0;
  17433. for (var f = 0; f < l; f++) {
  17434. var sind = this._depthSortedFacets[f].ind;
  17435. this._depthSortedIndices[f * 3] = indices[sind];
  17436. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17437. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17438. }
  17439. this.updateIndices(this._depthSortedIndices);
  17440. }
  17441. return this;
  17442. };
  17443. /**
  17444. * Returns the facetLocalNormals array.
  17445. * The normals are expressed in the mesh local space.
  17446. */
  17447. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17448. if (!this._facetNormals) {
  17449. this.updateFacetData();
  17450. }
  17451. return this._facetNormals;
  17452. };
  17453. /**
  17454. * Returns the facetLocalPositions array.
  17455. * The facet positions are expressed in the mesh local space.
  17456. */
  17457. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17458. if (!this._facetPositions) {
  17459. this.updateFacetData();
  17460. }
  17461. return this._facetPositions;
  17462. };
  17463. /**
  17464. * Returns the facetLocalPartioning array.
  17465. */
  17466. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17467. if (!this._facetPartitioning) {
  17468. this.updateFacetData();
  17469. }
  17470. return this._facetPartitioning;
  17471. };
  17472. /**
  17473. * Returns the i-th facet position in the world system.
  17474. * This method allocates a new Vector3 per call.
  17475. */
  17476. AbstractMesh.prototype.getFacetPosition = function (i) {
  17477. var pos = BABYLON.Vector3.Zero();
  17478. this.getFacetPositionToRef(i, pos);
  17479. return pos;
  17480. };
  17481. /**
  17482. * Sets the reference Vector3 with the i-th facet position in the world system.
  17483. * Returns the AbstractMesh.
  17484. */
  17485. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17486. var localPos = (this.getFacetLocalPositions())[i];
  17487. var world = this.getWorldMatrix();
  17488. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17489. return this;
  17490. };
  17491. /**
  17492. * Returns the i-th facet normal in the world system.
  17493. * This method allocates a new Vector3 per call.
  17494. */
  17495. AbstractMesh.prototype.getFacetNormal = function (i) {
  17496. var norm = BABYLON.Vector3.Zero();
  17497. this.getFacetNormalToRef(i, norm);
  17498. return norm;
  17499. };
  17500. /**
  17501. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17502. * Returns the AbstractMesh.
  17503. */
  17504. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17505. var localNorm = (this.getFacetLocalNormals())[i];
  17506. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17507. return this;
  17508. };
  17509. /**
  17510. * 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).
  17511. */
  17512. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17513. var bInfo = this.getBoundingInfo();
  17514. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17515. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17516. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17517. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17518. return null;
  17519. }
  17520. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17521. };
  17522. /**
  17523. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17524. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17525. * 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.
  17526. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17527. * 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.
  17528. */
  17529. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17530. if (checkFace === void 0) { checkFace = false; }
  17531. if (facing === void 0) { facing = true; }
  17532. var world = this.getWorldMatrix();
  17533. var invMat = BABYLON.Tmp.Matrix[5];
  17534. world.invertToRef(invMat);
  17535. var invVect = BABYLON.Tmp.Vector3[8];
  17536. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17537. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17538. if (projected) {
  17539. // tranform the local computed projected vector to world coordinates
  17540. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17541. }
  17542. return closest;
  17543. };
  17544. /**
  17545. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17546. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17547. * 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.
  17548. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17549. * 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.
  17550. */
  17551. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17552. if (checkFace === void 0) { checkFace = false; }
  17553. if (facing === void 0) { facing = true; }
  17554. var closest = null;
  17555. var tmpx = 0.0;
  17556. var tmpy = 0.0;
  17557. var tmpz = 0.0;
  17558. var d = 0.0; // tmp dot facet normal * facet position
  17559. var t0 = 0.0;
  17560. var projx = 0.0;
  17561. var projy = 0.0;
  17562. var projz = 0.0;
  17563. // Get all the facets in the same partitioning block than (x, y, z)
  17564. var facetPositions = this.getFacetLocalPositions();
  17565. var facetNormals = this.getFacetLocalNormals();
  17566. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17567. if (!facetsInBlock) {
  17568. return null;
  17569. }
  17570. // Get the closest facet to (x, y, z)
  17571. var shortest = Number.MAX_VALUE; // init distance vars
  17572. var tmpDistance = shortest;
  17573. var fib; // current facet in the block
  17574. var norm; // current facet normal
  17575. var p0; // current facet barycenter position
  17576. // loop on all the facets in the current partitioning block
  17577. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17578. fib = facetsInBlock[idx];
  17579. norm = facetNormals[fib];
  17580. p0 = facetPositions[fib];
  17581. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17582. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17583. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17584. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17585. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17586. projx = x + norm.x * t0;
  17587. projy = y + norm.y * t0;
  17588. projz = z + norm.z * t0;
  17589. tmpx = projx - x;
  17590. tmpy = projy - y;
  17591. tmpz = projz - z;
  17592. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17593. if (tmpDistance < shortest) {
  17594. shortest = tmpDistance;
  17595. closest = fib;
  17596. if (projected) {
  17597. projected.x = projx;
  17598. projected.y = projy;
  17599. projected.z = projz;
  17600. }
  17601. }
  17602. }
  17603. }
  17604. return closest;
  17605. };
  17606. /**
  17607. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17608. */
  17609. AbstractMesh.prototype.getFacetDataParameters = function () {
  17610. return this._facetParameters;
  17611. };
  17612. /**
  17613. * Disables the feature FacetData and frees the related memory.
  17614. * Returns the AbstractMesh.
  17615. */
  17616. AbstractMesh.prototype.disableFacetData = function () {
  17617. if (this._facetDataEnabled) {
  17618. this._facetDataEnabled = false;
  17619. this._facetPositions = new Array();
  17620. this._facetNormals = new Array();
  17621. this._facetPartitioning = new Array();
  17622. this._facetParameters = null;
  17623. this._depthSortedIndices = new Uint32Array(0);
  17624. }
  17625. return this;
  17626. };
  17627. /**
  17628. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17629. * Returns the mesh.
  17630. */
  17631. AbstractMesh.prototype.updateIndices = function (indices) {
  17632. return this;
  17633. };
  17634. /**
  17635. * The mesh Geometry. Actually used by the Mesh object.
  17636. * Returns a blank geometry object.
  17637. */
  17638. /**
  17639. * Creates new normals data for the mesh.
  17640. * @param updatable.
  17641. */
  17642. AbstractMesh.prototype.createNormals = function (updatable) {
  17643. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17644. var indices = this.getIndices();
  17645. var normals;
  17646. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17647. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17648. }
  17649. else {
  17650. normals = [];
  17651. }
  17652. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17653. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17654. };
  17655. /**
  17656. * Align the mesh with a normal.
  17657. * Returns the mesh.
  17658. */
  17659. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17660. if (!upDirection) {
  17661. upDirection = BABYLON.Axis.Y;
  17662. }
  17663. var axisX = BABYLON.Tmp.Vector3[0];
  17664. var axisZ = BABYLON.Tmp.Vector3[1];
  17665. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17666. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17667. if (this.rotationQuaternion) {
  17668. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17669. }
  17670. else {
  17671. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17672. }
  17673. return this;
  17674. };
  17675. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17676. var engine = this.getEngine();
  17677. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17678. this._isOccluded = false;
  17679. return;
  17680. }
  17681. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17682. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17683. if (isOcclusionQueryAvailable) {
  17684. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17685. this._isOcclusionQueryInProgress = false;
  17686. this._occlusionInternalRetryCounter = 0;
  17687. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17688. }
  17689. else {
  17690. this._occlusionInternalRetryCounter++;
  17691. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17692. this._isOcclusionQueryInProgress = false;
  17693. this._occlusionInternalRetryCounter = 0;
  17694. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17695. // if strict continue the last state of the object.
  17696. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17697. }
  17698. else {
  17699. return;
  17700. }
  17701. }
  17702. }
  17703. var scene = this.getScene();
  17704. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17705. if (!this._occlusionQuery) {
  17706. this._occlusionQuery = engine.createQuery();
  17707. }
  17708. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17709. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17710. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17711. this._isOcclusionQueryInProgress = true;
  17712. };
  17713. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17714. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17715. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17716. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17717. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17718. return AbstractMesh;
  17719. }(BABYLON.TransformNode));
  17720. BABYLON.AbstractMesh = AbstractMesh;
  17721. })(BABYLON || (BABYLON = {}));
  17722. //# sourceMappingURL=babylon.abstractMesh.js.map
  17723. var BABYLON;
  17724. (function (BABYLON) {
  17725. /**
  17726. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17727. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17728. * 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.
  17729. */
  17730. var Light = /** @class */ (function (_super) {
  17731. __extends(Light, _super);
  17732. /**
  17733. * Creates a Light object in the scene.
  17734. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17735. * @param name The firendly name of the light
  17736. * @param scene The scene the light belongs too
  17737. */
  17738. function Light(name, scene) {
  17739. var _this = _super.call(this, name, scene) || this;
  17740. /**
  17741. * Diffuse gives the basic color to an object.
  17742. */
  17743. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17744. /**
  17745. * Specular produces a highlight color on an object.
  17746. * Note: This is note affecting PBR materials.
  17747. */
  17748. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17749. /**
  17750. * Strength of the light.
  17751. * Note: By default it is define in the framework own unit.
  17752. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17753. */
  17754. _this.intensity = 1.0;
  17755. /**
  17756. * Defines how far from the source the light is impacting in scene units.
  17757. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17758. */
  17759. _this.range = Number.MAX_VALUE;
  17760. /**
  17761. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17762. * of light.
  17763. */
  17764. _this._photometricScale = 1.0;
  17765. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17766. _this._radius = 0.00001;
  17767. /**
  17768. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17769. * exceeding the number allowed of the materials.
  17770. */
  17771. _this.renderPriority = 0;
  17772. /**
  17773. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17774. * the current shadow generator.
  17775. */
  17776. _this.shadowEnabled = true;
  17777. _this._excludeWithLayerMask = 0;
  17778. _this._includeOnlyWithLayerMask = 0;
  17779. _this._lightmapMode = 0;
  17780. /**
  17781. * @ignore Internal use only.
  17782. */
  17783. _this._excludedMeshesIds = new Array();
  17784. /**
  17785. * @ignore Internal use only.
  17786. */
  17787. _this._includedOnlyMeshesIds = new Array();
  17788. _this.getScene().addLight(_this);
  17789. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17790. _this._buildUniformLayout();
  17791. _this.includedOnlyMeshes = new Array();
  17792. _this.excludedMeshes = new Array();
  17793. _this._resyncMeshes();
  17794. return _this;
  17795. }
  17796. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17797. /**
  17798. * If every light affecting the material is in this lightmapMode,
  17799. * material.lightmapTexture adds or multiplies
  17800. * (depends on material.useLightmapAsShadowmap)
  17801. * after every other light calculations.
  17802. */
  17803. get: function () {
  17804. return Light._LIGHTMAP_DEFAULT;
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17810. /**
  17811. * material.lightmapTexture as only diffuse lighting from this light
  17812. * adds only specular lighting from this light
  17813. * adds dynamic shadows
  17814. */
  17815. get: function () {
  17816. return Light._LIGHTMAP_SPECULAR;
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17822. /**
  17823. * material.lightmapTexture as only lighting
  17824. * no light calculation from this light
  17825. * only adds dynamic shadows from this light
  17826. */
  17827. get: function () {
  17828. return Light._LIGHTMAP_SHADOWSONLY;
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17834. /**
  17835. * Each light type uses the default quantity according to its type:
  17836. * point/spot lights use luminous intensity
  17837. * directional lights use illuminance
  17838. */
  17839. get: function () {
  17840. return Light._INTENSITYMODE_AUTOMATIC;
  17841. },
  17842. enumerable: true,
  17843. configurable: true
  17844. });
  17845. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17846. /**
  17847. * lumen (lm)
  17848. */
  17849. get: function () {
  17850. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17856. /**
  17857. * candela (lm/sr)
  17858. */
  17859. get: function () {
  17860. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17866. /**
  17867. * lux (lm/m^2)
  17868. */
  17869. get: function () {
  17870. return Light._INTENSITYMODE_ILLUMINANCE;
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17876. /**
  17877. * nit (cd/m^2)
  17878. */
  17879. get: function () {
  17880. return Light._INTENSITYMODE_LUMINANCE;
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17886. /**
  17887. * Light type const id of the point light.
  17888. */
  17889. get: function () {
  17890. return Light._LIGHTTYPEID_POINTLIGHT;
  17891. },
  17892. enumerable: true,
  17893. configurable: true
  17894. });
  17895. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17896. /**
  17897. * Light type const id of the directional light.
  17898. */
  17899. get: function () {
  17900. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17906. /**
  17907. * Light type const id of the spot light.
  17908. */
  17909. get: function () {
  17910. return Light._LIGHTTYPEID_SPOTLIGHT;
  17911. },
  17912. enumerable: true,
  17913. configurable: true
  17914. });
  17915. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17916. /**
  17917. * Light type const id of the hemispheric light.
  17918. */
  17919. get: function () {
  17920. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Object.defineProperty(Light.prototype, "intensityMode", {
  17926. /**
  17927. * Gets the photometric scale used to interpret the intensity.
  17928. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17929. */
  17930. get: function () {
  17931. return this._intensityMode;
  17932. },
  17933. /**
  17934. * Sets the photometric scale used to interpret the intensity.
  17935. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17936. */
  17937. set: function (value) {
  17938. this._intensityMode = value;
  17939. this._computePhotometricScale();
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. ;
  17945. ;
  17946. Object.defineProperty(Light.prototype, "radius", {
  17947. /**
  17948. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17949. */
  17950. get: function () {
  17951. return this._radius;
  17952. },
  17953. /**
  17954. * sets the light radius used by PBR Materials to simulate soft area lights.
  17955. */
  17956. set: function (value) {
  17957. this._radius = value;
  17958. this._computePhotometricScale();
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. ;
  17964. ;
  17965. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17966. /**
  17967. * Gets the only meshes impacted by this light.
  17968. */
  17969. get: function () {
  17970. return this._includedOnlyMeshes;
  17971. },
  17972. /**
  17973. * Sets the only meshes impacted by this light.
  17974. */
  17975. set: function (value) {
  17976. this._includedOnlyMeshes = value;
  17977. this._hookArrayForIncludedOnly(value);
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17983. /**
  17984. * Gets the meshes not impacted by this light.
  17985. */
  17986. get: function () {
  17987. return this._excludedMeshes;
  17988. },
  17989. /**
  17990. * Sets the meshes not impacted by this light.
  17991. */
  17992. set: function (value) {
  17993. this._excludedMeshes = value;
  17994. this._hookArrayForExcluded(value);
  17995. },
  17996. enumerable: true,
  17997. configurable: true
  17998. });
  17999. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18000. /**
  18001. * Gets the layer id use to find what meshes are not impacted by the light.
  18002. * Inactive if 0
  18003. */
  18004. get: function () {
  18005. return this._excludeWithLayerMask;
  18006. },
  18007. /**
  18008. * Sets the layer id use to find what meshes are not impacted by the light.
  18009. * Inactive if 0
  18010. */
  18011. set: function (value) {
  18012. this._excludeWithLayerMask = value;
  18013. this._resyncMeshes();
  18014. },
  18015. enumerable: true,
  18016. configurable: true
  18017. });
  18018. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18019. /**
  18020. * Gets the layer id use to find what meshes are impacted by the light.
  18021. * Inactive if 0
  18022. */
  18023. get: function () {
  18024. return this._includeOnlyWithLayerMask;
  18025. },
  18026. /**
  18027. * Sets the layer id use to find what meshes are impacted by the light.
  18028. * Inactive if 0
  18029. */
  18030. set: function (value) {
  18031. this._includeOnlyWithLayerMask = value;
  18032. this._resyncMeshes();
  18033. },
  18034. enumerable: true,
  18035. configurable: true
  18036. });
  18037. Object.defineProperty(Light.prototype, "lightmapMode", {
  18038. /**
  18039. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18040. */
  18041. get: function () {
  18042. return this._lightmapMode;
  18043. },
  18044. /**
  18045. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18046. */
  18047. set: function (value) {
  18048. if (this._lightmapMode === value) {
  18049. return;
  18050. }
  18051. this._lightmapMode = value;
  18052. this._markMeshesAsLightDirty();
  18053. },
  18054. enumerable: true,
  18055. configurable: true
  18056. });
  18057. /**
  18058. * Returns the string "Light".
  18059. * @returns the class name
  18060. */
  18061. Light.prototype.getClassName = function () {
  18062. return "Light";
  18063. };
  18064. /**
  18065. * Converts the light information to a readable string for debug purpose.
  18066. * @param fullDetails Supports for multiple levels of logging within scene loading
  18067. * @returns the human readable light info
  18068. */
  18069. Light.prototype.toString = function (fullDetails) {
  18070. var ret = "Name: " + this.name;
  18071. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18072. if (this.animations) {
  18073. for (var i = 0; i < this.animations.length; i++) {
  18074. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18075. }
  18076. }
  18077. if (fullDetails) {
  18078. }
  18079. return ret;
  18080. };
  18081. /**
  18082. * Set the enabled state of this node.
  18083. * @param value - the new enabled state
  18084. * @see isEnabled
  18085. */
  18086. Light.prototype.setEnabled = function (value) {
  18087. _super.prototype.setEnabled.call(this, value);
  18088. this._resyncMeshes();
  18089. };
  18090. /**
  18091. * Returns the Light associated shadow generator if any.
  18092. * @return the associated shadow generator.
  18093. */
  18094. Light.prototype.getShadowGenerator = function () {
  18095. return this._shadowGenerator;
  18096. };
  18097. /**
  18098. * Returns a Vector3, the absolute light position in the World.
  18099. * @returns the world space position of the light
  18100. */
  18101. Light.prototype.getAbsolutePosition = function () {
  18102. return BABYLON.Vector3.Zero();
  18103. };
  18104. /**
  18105. * Specifies if the light will affect the passed mesh.
  18106. * @param mesh The mesh to test against the light
  18107. * @return true the mesh is affected otherwise, false.
  18108. */
  18109. Light.prototype.canAffectMesh = function (mesh) {
  18110. if (!mesh) {
  18111. return true;
  18112. }
  18113. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18114. return false;
  18115. }
  18116. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18117. return false;
  18118. }
  18119. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18120. return false;
  18121. }
  18122. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18123. return false;
  18124. }
  18125. return true;
  18126. };
  18127. /**
  18128. * Computes and Returns the light World matrix.
  18129. * @returns the world matrix
  18130. */
  18131. Light.prototype.getWorldMatrix = function () {
  18132. this._currentRenderId = this.getScene().getRenderId();
  18133. var worldMatrix = this._getWorldMatrix();
  18134. if (this.parent && this.parent.getWorldMatrix) {
  18135. if (!this._parentedWorldMatrix) {
  18136. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18137. }
  18138. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18139. this._markSyncedWithParent();
  18140. return this._parentedWorldMatrix;
  18141. }
  18142. return worldMatrix;
  18143. };
  18144. /**
  18145. * Sort function to order lights for rendering.
  18146. * @param a First Light object to compare to second.
  18147. * @param b Second Light object to compare first.
  18148. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18149. */
  18150. Light.CompareLightsPriority = function (a, b) {
  18151. //shadow-casting lights have priority over non-shadow-casting lights
  18152. //the renderPrioirty is a secondary sort criterion
  18153. if (a.shadowEnabled !== b.shadowEnabled) {
  18154. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18155. }
  18156. return b.renderPriority - a.renderPriority;
  18157. };
  18158. /**
  18159. * Disposes the light.
  18160. */
  18161. Light.prototype.dispose = function () {
  18162. if (this._shadowGenerator) {
  18163. this._shadowGenerator.dispose();
  18164. this._shadowGenerator = null;
  18165. }
  18166. // Animations
  18167. this.getScene().stopAnimation(this);
  18168. // Remove from meshes
  18169. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18170. var mesh = _a[_i];
  18171. mesh._removeLightSource(this);
  18172. }
  18173. this._uniformBuffer.dispose();
  18174. // Remove from scene
  18175. this.getScene().removeLight(this);
  18176. _super.prototype.dispose.call(this);
  18177. };
  18178. /**
  18179. * Returns the light type ID (integer).
  18180. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18181. */
  18182. Light.prototype.getTypeID = function () {
  18183. return 0;
  18184. };
  18185. /**
  18186. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18187. * @returns the scaled intensity in intensity mode unit
  18188. */
  18189. Light.prototype.getScaledIntensity = function () {
  18190. return this._photometricScale * this.intensity;
  18191. };
  18192. /**
  18193. * Returns a new Light object, named "name", from the current one.
  18194. * @param name The name of the cloned light
  18195. * @returns the new created light
  18196. */
  18197. Light.prototype.clone = function (name) {
  18198. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18199. if (!constructor) {
  18200. return null;
  18201. }
  18202. return BABYLON.SerializationHelper.Clone(constructor, this);
  18203. };
  18204. /**
  18205. * Serializes the current light into a Serialization object.
  18206. * @returns the serialized object.
  18207. */
  18208. Light.prototype.serialize = function () {
  18209. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18210. // Type
  18211. serializationObject.type = this.getTypeID();
  18212. // Parent
  18213. if (this.parent) {
  18214. serializationObject.parentId = this.parent.id;
  18215. }
  18216. // Inclusion / exclusions
  18217. if (this.excludedMeshes.length > 0) {
  18218. serializationObject.excludedMeshesIds = [];
  18219. this.excludedMeshes.forEach(function (mesh) {
  18220. serializationObject.excludedMeshesIds.push(mesh.id);
  18221. });
  18222. }
  18223. if (this.includedOnlyMeshes.length > 0) {
  18224. serializationObject.includedOnlyMeshesIds = [];
  18225. this.includedOnlyMeshes.forEach(function (mesh) {
  18226. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18227. });
  18228. }
  18229. // Animations
  18230. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18231. serializationObject.ranges = this.serializeAnimationRanges();
  18232. return serializationObject;
  18233. };
  18234. /**
  18235. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18236. * This new light is named "name" and added to the passed scene.
  18237. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18238. * @param name The friendly name of the light
  18239. * @param scene The scene the new light will belong to
  18240. * @returns the constructor function
  18241. */
  18242. Light.GetConstructorFromName = function (type, name, scene) {
  18243. switch (type) {
  18244. case 0:
  18245. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18246. case 1:
  18247. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18248. case 2:
  18249. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18250. case 3:
  18251. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18252. }
  18253. return null;
  18254. };
  18255. /**
  18256. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18257. * @param parsedLight The JSON representation of the light
  18258. * @param scene The scene to create the parsed light in
  18259. * @returns the created light after parsing
  18260. */
  18261. Light.Parse = function (parsedLight, scene) {
  18262. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18263. if (!constructor) {
  18264. return null;
  18265. }
  18266. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18267. // Inclusion / exclusions
  18268. if (parsedLight.excludedMeshesIds) {
  18269. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18270. }
  18271. if (parsedLight.includedOnlyMeshesIds) {
  18272. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18273. }
  18274. // Parent
  18275. if (parsedLight.parentId) {
  18276. light._waitingParentId = parsedLight.parentId;
  18277. }
  18278. // Animations
  18279. if (parsedLight.animations) {
  18280. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18281. var parsedAnimation = parsedLight.animations[animationIndex];
  18282. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18283. }
  18284. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18285. }
  18286. if (parsedLight.autoAnimate) {
  18287. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18288. }
  18289. return light;
  18290. };
  18291. Light.prototype._hookArrayForExcluded = function (array) {
  18292. var _this = this;
  18293. var oldPush = array.push;
  18294. array.push = function () {
  18295. var items = [];
  18296. for (var _i = 0; _i < arguments.length; _i++) {
  18297. items[_i] = arguments[_i];
  18298. }
  18299. var result = oldPush.apply(array, items);
  18300. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18301. var item = items_1[_a];
  18302. item._resyncLighSource(_this);
  18303. }
  18304. return result;
  18305. };
  18306. var oldSplice = array.splice;
  18307. array.splice = function (index, deleteCount) {
  18308. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18309. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18310. var item = deleted_1[_i];
  18311. item._resyncLighSource(_this);
  18312. }
  18313. return deleted;
  18314. };
  18315. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18316. var item = array_1[_i];
  18317. item._resyncLighSource(this);
  18318. }
  18319. };
  18320. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18321. var _this = this;
  18322. var oldPush = array.push;
  18323. array.push = function () {
  18324. var items = [];
  18325. for (var _i = 0; _i < arguments.length; _i++) {
  18326. items[_i] = arguments[_i];
  18327. }
  18328. var result = oldPush.apply(array, items);
  18329. _this._resyncMeshes();
  18330. return result;
  18331. };
  18332. var oldSplice = array.splice;
  18333. array.splice = function (index, deleteCount) {
  18334. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18335. _this._resyncMeshes();
  18336. return deleted;
  18337. };
  18338. this._resyncMeshes();
  18339. };
  18340. Light.prototype._resyncMeshes = function () {
  18341. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18342. var mesh = _a[_i];
  18343. mesh._resyncLighSource(this);
  18344. }
  18345. };
  18346. /**
  18347. * Forces the meshes to update their light related information in their rendering used effects
  18348. * @ignore Internal Use Only
  18349. */
  18350. Light.prototype._markMeshesAsLightDirty = function () {
  18351. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18352. var mesh = _a[_i];
  18353. if (mesh._lightSources.indexOf(this) !== -1) {
  18354. mesh._markSubMeshesAsLightDirty();
  18355. }
  18356. }
  18357. };
  18358. /**
  18359. * Recomputes the cached photometric scale if needed.
  18360. */
  18361. Light.prototype._computePhotometricScale = function () {
  18362. this._photometricScale = this._getPhotometricScale();
  18363. this.getScene().resetCachedMaterial();
  18364. };
  18365. /**
  18366. * Returns the Photometric Scale according to the light type and intensity mode.
  18367. */
  18368. Light.prototype._getPhotometricScale = function () {
  18369. var photometricScale = 0.0;
  18370. var lightTypeID = this.getTypeID();
  18371. //get photometric mode
  18372. var photometricMode = this.intensityMode;
  18373. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18374. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18375. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18376. }
  18377. else {
  18378. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18379. }
  18380. }
  18381. //compute photometric scale
  18382. switch (lightTypeID) {
  18383. case Light.LIGHTTYPEID_POINTLIGHT:
  18384. case Light.LIGHTTYPEID_SPOTLIGHT:
  18385. switch (photometricMode) {
  18386. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18387. photometricScale = 1.0 / (4.0 * Math.PI);
  18388. break;
  18389. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18390. photometricScale = 1.0;
  18391. break;
  18392. case Light.INTENSITYMODE_LUMINANCE:
  18393. photometricScale = this.radius * this.radius;
  18394. break;
  18395. }
  18396. break;
  18397. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18398. switch (photometricMode) {
  18399. case Light.INTENSITYMODE_ILLUMINANCE:
  18400. photometricScale = 1.0;
  18401. break;
  18402. case Light.INTENSITYMODE_LUMINANCE:
  18403. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18404. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18405. var apexAngleRadians = this.radius;
  18406. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18407. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18408. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18409. photometricScale = solidAngle;
  18410. break;
  18411. }
  18412. break;
  18413. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18414. // No fall off in hemisperic light.
  18415. photometricScale = 1.0;
  18416. break;
  18417. }
  18418. return photometricScale;
  18419. };
  18420. /**
  18421. * Reorder the light in the scene according to their defined priority.
  18422. * @ignore Internal Use Only
  18423. */
  18424. Light.prototype._reorderLightsInScene = function () {
  18425. var scene = this.getScene();
  18426. if (this._renderPriority != 0) {
  18427. scene.requireLightSorting = true;
  18428. }
  18429. this.getScene().sortLightsByPriority();
  18430. };
  18431. //lightmapMode Consts
  18432. Light._LIGHTMAP_DEFAULT = 0;
  18433. Light._LIGHTMAP_SPECULAR = 1;
  18434. Light._LIGHTMAP_SHADOWSONLY = 2;
  18435. // Intensity Mode Consts
  18436. Light._INTENSITYMODE_AUTOMATIC = 0;
  18437. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18438. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18439. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18440. Light._INTENSITYMODE_LUMINANCE = 4;
  18441. // Light types ids const.
  18442. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18443. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18444. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18445. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18446. __decorate([
  18447. BABYLON.serializeAsColor3()
  18448. ], Light.prototype, "diffuse", void 0);
  18449. __decorate([
  18450. BABYLON.serializeAsColor3()
  18451. ], Light.prototype, "specular", void 0);
  18452. __decorate([
  18453. BABYLON.serialize()
  18454. ], Light.prototype, "intensity", void 0);
  18455. __decorate([
  18456. BABYLON.serialize()
  18457. ], Light.prototype, "range", void 0);
  18458. __decorate([
  18459. BABYLON.serialize()
  18460. ], Light.prototype, "intensityMode", null);
  18461. __decorate([
  18462. BABYLON.serialize()
  18463. ], Light.prototype, "radius", null);
  18464. __decorate([
  18465. BABYLON.serialize()
  18466. ], Light.prototype, "_renderPriority", void 0);
  18467. __decorate([
  18468. BABYLON.expandToProperty("_reorderLightsInScene")
  18469. ], Light.prototype, "renderPriority", void 0);
  18470. __decorate([
  18471. BABYLON.serialize()
  18472. ], Light.prototype, "shadowEnabled", void 0);
  18473. __decorate([
  18474. BABYLON.serialize("excludeWithLayerMask")
  18475. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18476. __decorate([
  18477. BABYLON.serialize("includeOnlyWithLayerMask")
  18478. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18479. __decorate([
  18480. BABYLON.serialize("lightmapMode")
  18481. ], Light.prototype, "_lightmapMode", void 0);
  18482. return Light;
  18483. }(BABYLON.Node));
  18484. BABYLON.Light = Light;
  18485. })(BABYLON || (BABYLON = {}));
  18486. //# sourceMappingURL=babylon.light.js.map
  18487. var BABYLON;
  18488. (function (BABYLON) {
  18489. var Camera = /** @class */ (function (_super) {
  18490. __extends(Camera, _super);
  18491. function Camera(name, position, scene) {
  18492. var _this = _super.call(this, name, scene) || this;
  18493. /**
  18494. * The vector the camera should consider as up.
  18495. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18496. */
  18497. _this.upVector = BABYLON.Vector3.Up();
  18498. _this.orthoLeft = null;
  18499. _this.orthoRight = null;
  18500. _this.orthoBottom = null;
  18501. _this.orthoTop = null;
  18502. /**
  18503. * FOV is set in Radians. (default is 0.8)
  18504. */
  18505. _this.fov = 0.8;
  18506. _this.minZ = 1;
  18507. _this.maxZ = 10000.0;
  18508. _this.inertia = 0.9;
  18509. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18510. _this.isIntermediate = false;
  18511. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18512. /**
  18513. * Restricts the camera to viewing objects with the same layerMask.
  18514. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18515. */
  18516. _this.layerMask = 0x0FFFFFFF;
  18517. /**
  18518. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18519. */
  18520. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18521. // Camera rig members
  18522. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18523. _this._rigCameras = new Array();
  18524. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18525. _this._skipRendering = false;
  18526. _this.customRenderTargets = new Array();
  18527. // Observables
  18528. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18529. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18530. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18531. _this.onRestoreStateObservable = new BABYLON.Observable();
  18532. // Cache
  18533. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18534. _this._projectionMatrix = new BABYLON.Matrix();
  18535. _this._doNotComputeProjectionMatrix = false;
  18536. _this._postProcesses = new Array();
  18537. _this._transformMatrix = BABYLON.Matrix.Zero();
  18538. _this._activeMeshes = new BABYLON.SmartArray(256);
  18539. _this._globalPosition = BABYLON.Vector3.Zero();
  18540. _this._refreshFrustumPlanes = true;
  18541. _this.getScene().addCamera(_this);
  18542. if (!_this.getScene().activeCamera) {
  18543. _this.getScene().activeCamera = _this;
  18544. }
  18545. _this.position = position;
  18546. return _this;
  18547. }
  18548. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18549. get: function () {
  18550. return Camera._PERSPECTIVE_CAMERA;
  18551. },
  18552. enumerable: true,
  18553. configurable: true
  18554. });
  18555. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18556. get: function () {
  18557. return Camera._ORTHOGRAPHIC_CAMERA;
  18558. },
  18559. enumerable: true,
  18560. configurable: true
  18561. });
  18562. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18563. /**
  18564. * This is the default FOV mode for perspective cameras.
  18565. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18566. *
  18567. */
  18568. get: function () {
  18569. return Camera._FOVMODE_VERTICAL_FIXED;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18575. /**
  18576. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18577. *
  18578. */
  18579. get: function () {
  18580. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18581. },
  18582. enumerable: true,
  18583. configurable: true
  18584. });
  18585. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18586. get: function () {
  18587. return Camera._RIG_MODE_NONE;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18593. get: function () {
  18594. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18600. get: function () {
  18601. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18607. get: function () {
  18608. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18609. },
  18610. enumerable: true,
  18611. configurable: true
  18612. });
  18613. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18614. get: function () {
  18615. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18616. },
  18617. enumerable: true,
  18618. configurable: true
  18619. });
  18620. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18621. get: function () {
  18622. return Camera._RIG_MODE_VR;
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18628. get: function () {
  18629. return Camera._RIG_MODE_WEBVR;
  18630. },
  18631. enumerable: true,
  18632. configurable: true
  18633. });
  18634. /**
  18635. * Store current camera state (fov, position, etc..)
  18636. */
  18637. Camera.prototype.storeState = function () {
  18638. this._stateStored = true;
  18639. this._storedFov = this.fov;
  18640. return this;
  18641. };
  18642. /**
  18643. * Restores the camera state values if it has been stored. You must call storeState() first
  18644. */
  18645. Camera.prototype._restoreStateValues = function () {
  18646. if (!this._stateStored) {
  18647. return false;
  18648. }
  18649. this.fov = this._storedFov;
  18650. return true;
  18651. };
  18652. /**
  18653. * Restored camera state. You must call storeState() first
  18654. */
  18655. Camera.prototype.restoreState = function () {
  18656. if (this._restoreStateValues()) {
  18657. this.onRestoreStateObservable.notifyObservers(this);
  18658. return true;
  18659. }
  18660. return false;
  18661. };
  18662. Camera.prototype.getClassName = function () {
  18663. return "Camera";
  18664. };
  18665. /**
  18666. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18667. */
  18668. Camera.prototype.toString = function (fullDetails) {
  18669. var ret = "Name: " + this.name;
  18670. ret += ", type: " + this.getClassName();
  18671. if (this.animations) {
  18672. for (var i = 0; i < this.animations.length; i++) {
  18673. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18674. }
  18675. }
  18676. if (fullDetails) {
  18677. }
  18678. return ret;
  18679. };
  18680. Object.defineProperty(Camera.prototype, "globalPosition", {
  18681. get: function () {
  18682. return this._globalPosition;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Camera.prototype.getActiveMeshes = function () {
  18688. return this._activeMeshes;
  18689. };
  18690. Camera.prototype.isActiveMesh = function (mesh) {
  18691. return (this._activeMeshes.indexOf(mesh) !== -1);
  18692. };
  18693. //Cache
  18694. Camera.prototype._initCache = function () {
  18695. _super.prototype._initCache.call(this);
  18696. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18697. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18698. this._cache.mode = undefined;
  18699. this._cache.minZ = undefined;
  18700. this._cache.maxZ = undefined;
  18701. this._cache.fov = undefined;
  18702. this._cache.fovMode = undefined;
  18703. this._cache.aspectRatio = undefined;
  18704. this._cache.orthoLeft = undefined;
  18705. this._cache.orthoRight = undefined;
  18706. this._cache.orthoBottom = undefined;
  18707. this._cache.orthoTop = undefined;
  18708. this._cache.renderWidth = undefined;
  18709. this._cache.renderHeight = undefined;
  18710. };
  18711. Camera.prototype._updateCache = function (ignoreParentClass) {
  18712. if (!ignoreParentClass) {
  18713. _super.prototype._updateCache.call(this);
  18714. }
  18715. this._cache.position.copyFrom(this.position);
  18716. this._cache.upVector.copyFrom(this.upVector);
  18717. };
  18718. // Synchronized
  18719. Camera.prototype._isSynchronized = function () {
  18720. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18721. };
  18722. Camera.prototype._isSynchronizedViewMatrix = function () {
  18723. if (!_super.prototype._isSynchronized.call(this))
  18724. return false;
  18725. return this._cache.position.equals(this.position)
  18726. && this._cache.upVector.equals(this.upVector)
  18727. && this.isSynchronizedWithParent();
  18728. };
  18729. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18730. var check = this._cache.mode === this.mode
  18731. && this._cache.minZ === this.minZ
  18732. && this._cache.maxZ === this.maxZ;
  18733. if (!check) {
  18734. return false;
  18735. }
  18736. var engine = this.getEngine();
  18737. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18738. check = this._cache.fov === this.fov
  18739. && this._cache.fovMode === this.fovMode
  18740. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18741. }
  18742. else {
  18743. check = this._cache.orthoLeft === this.orthoLeft
  18744. && this._cache.orthoRight === this.orthoRight
  18745. && this._cache.orthoBottom === this.orthoBottom
  18746. && this._cache.orthoTop === this.orthoTop
  18747. && this._cache.renderWidth === engine.getRenderWidth()
  18748. && this._cache.renderHeight === engine.getRenderHeight();
  18749. }
  18750. return check;
  18751. };
  18752. // Controls
  18753. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18754. };
  18755. Camera.prototype.detachControl = function (element) {
  18756. };
  18757. Camera.prototype.update = function () {
  18758. this._checkInputs();
  18759. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18760. this._updateRigCameras();
  18761. }
  18762. };
  18763. Camera.prototype._checkInputs = function () {
  18764. this.onAfterCheckInputsObservable.notifyObservers(this);
  18765. };
  18766. Object.defineProperty(Camera.prototype, "rigCameras", {
  18767. get: function () {
  18768. return this._rigCameras;
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18774. get: function () {
  18775. return this._rigPostProcess;
  18776. },
  18777. enumerable: true,
  18778. configurable: true
  18779. });
  18780. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18781. // invalidate framebuffer
  18782. if (this._postProcesses.length > 0) {
  18783. this._postProcesses[0].markTextureDirty();
  18784. }
  18785. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18786. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18787. var cam = this._rigCameras[i];
  18788. var rigPostProcess = cam._rigPostProcess;
  18789. // for VR rig, there does not have to be a post process
  18790. if (rigPostProcess) {
  18791. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18792. if (isPass) {
  18793. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18794. cam.isIntermediate = this._postProcesses.length === 0;
  18795. }
  18796. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18797. rigPostProcess.markTextureDirty();
  18798. }
  18799. else {
  18800. cam._postProcesses = this._postProcesses.slice(0);
  18801. }
  18802. }
  18803. };
  18804. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18805. if (insertAt === void 0) { insertAt = null; }
  18806. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18807. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18808. return 0;
  18809. }
  18810. if (insertAt == null || insertAt < 0) {
  18811. this._postProcesses.push(postProcess);
  18812. }
  18813. else {
  18814. this._postProcesses.splice(insertAt, 0, postProcess);
  18815. }
  18816. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18817. return this._postProcesses.indexOf(postProcess);
  18818. };
  18819. Camera.prototype.detachPostProcess = function (postProcess) {
  18820. var idx = this._postProcesses.indexOf(postProcess);
  18821. if (idx !== -1) {
  18822. this._postProcesses.splice(idx, 1);
  18823. }
  18824. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18825. };
  18826. Camera.prototype.getWorldMatrix = function () {
  18827. if (!this._worldMatrix) {
  18828. this._worldMatrix = BABYLON.Matrix.Identity();
  18829. }
  18830. var viewMatrix = this.getViewMatrix();
  18831. viewMatrix.invertToRef(this._worldMatrix);
  18832. return this._worldMatrix;
  18833. };
  18834. Camera.prototype._getViewMatrix = function () {
  18835. return BABYLON.Matrix.Identity();
  18836. };
  18837. Camera.prototype.getViewMatrix = function (force) {
  18838. if (!force && this._isSynchronizedViewMatrix()) {
  18839. return this._computedViewMatrix;
  18840. }
  18841. this.updateCache();
  18842. this._computedViewMatrix = this._getViewMatrix();
  18843. this._currentRenderId = this.getScene().getRenderId();
  18844. this._refreshFrustumPlanes = true;
  18845. if (!this.parent || !this.parent.getWorldMatrix) {
  18846. this._globalPosition.copyFrom(this.position);
  18847. }
  18848. else {
  18849. if (!this._worldMatrix) {
  18850. this._worldMatrix = BABYLON.Matrix.Identity();
  18851. }
  18852. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18853. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18854. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18855. this._computedViewMatrix.invert();
  18856. this._markSyncedWithParent();
  18857. }
  18858. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18859. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18860. }
  18861. this.onViewMatrixChangedObservable.notifyObservers(this);
  18862. return this._computedViewMatrix;
  18863. };
  18864. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18865. this._doNotComputeProjectionMatrix = true;
  18866. if (projection !== undefined) {
  18867. this._projectionMatrix = projection;
  18868. }
  18869. };
  18870. ;
  18871. Camera.prototype.unfreezeProjectionMatrix = function () {
  18872. this._doNotComputeProjectionMatrix = false;
  18873. };
  18874. ;
  18875. Camera.prototype.getProjectionMatrix = function (force) {
  18876. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18877. return this._projectionMatrix;
  18878. }
  18879. // Cache
  18880. this._cache.mode = this.mode;
  18881. this._cache.minZ = this.minZ;
  18882. this._cache.maxZ = this.maxZ;
  18883. // Matrix
  18884. this._refreshFrustumPlanes = true;
  18885. var engine = this.getEngine();
  18886. var scene = this.getScene();
  18887. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18888. this._cache.fov = this.fov;
  18889. this._cache.fovMode = this.fovMode;
  18890. this._cache.aspectRatio = engine.getAspectRatio(this);
  18891. if (this.minZ <= 0) {
  18892. this.minZ = 0.1;
  18893. }
  18894. if (scene.useRightHandedSystem) {
  18895. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18896. }
  18897. else {
  18898. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18899. }
  18900. }
  18901. else {
  18902. var halfWidth = engine.getRenderWidth() / 2.0;
  18903. var halfHeight = engine.getRenderHeight() / 2.0;
  18904. if (scene.useRightHandedSystem) {
  18905. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18906. }
  18907. else {
  18908. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18909. }
  18910. this._cache.orthoLeft = this.orthoLeft;
  18911. this._cache.orthoRight = this.orthoRight;
  18912. this._cache.orthoBottom = this.orthoBottom;
  18913. this._cache.orthoTop = this.orthoTop;
  18914. this._cache.renderWidth = engine.getRenderWidth();
  18915. this._cache.renderHeight = engine.getRenderHeight();
  18916. }
  18917. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18918. return this._projectionMatrix;
  18919. };
  18920. Camera.prototype.getTranformationMatrix = function () {
  18921. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18922. return this._transformMatrix;
  18923. };
  18924. Camera.prototype.updateFrustumPlanes = function () {
  18925. if (!this._refreshFrustumPlanes) {
  18926. return;
  18927. }
  18928. this.getTranformationMatrix();
  18929. if (!this._frustumPlanes) {
  18930. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18931. }
  18932. else {
  18933. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18934. }
  18935. this._refreshFrustumPlanes = false;
  18936. };
  18937. Camera.prototype.isInFrustum = function (target) {
  18938. this.updateFrustumPlanes();
  18939. return target.isInFrustum(this._frustumPlanes);
  18940. };
  18941. Camera.prototype.isCompletelyInFrustum = function (target) {
  18942. this.updateFrustumPlanes();
  18943. return target.isCompletelyInFrustum(this._frustumPlanes);
  18944. };
  18945. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18946. if (length === void 0) { length = 100; }
  18947. if (!transform) {
  18948. transform = this.getWorldMatrix();
  18949. }
  18950. if (!origin) {
  18951. origin = this.position;
  18952. }
  18953. var forward = new BABYLON.Vector3(0, 0, 1);
  18954. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18955. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18956. return new BABYLON.Ray(origin, direction, length);
  18957. };
  18958. Camera.prototype.dispose = function () {
  18959. // Observables
  18960. this.onViewMatrixChangedObservable.clear();
  18961. this.onProjectionMatrixChangedObservable.clear();
  18962. this.onAfterCheckInputsObservable.clear();
  18963. this.onRestoreStateObservable.clear();
  18964. // Inputs
  18965. if (this.inputs) {
  18966. this.inputs.clear();
  18967. }
  18968. // Animations
  18969. this.getScene().stopAnimation(this);
  18970. // Remove from scene
  18971. this.getScene().removeCamera(this);
  18972. while (this._rigCameras.length > 0) {
  18973. var camera = this._rigCameras.pop();
  18974. if (camera) {
  18975. camera.dispose();
  18976. }
  18977. }
  18978. // Postprocesses
  18979. if (this._rigPostProcess) {
  18980. this._rigPostProcess.dispose(this);
  18981. this._rigPostProcess = null;
  18982. this._postProcesses = [];
  18983. }
  18984. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18985. this._rigPostProcess = null;
  18986. this._postProcesses = [];
  18987. }
  18988. else {
  18989. var i = this._postProcesses.length;
  18990. while (--i >= 0) {
  18991. this._postProcesses[i].dispose(this);
  18992. }
  18993. }
  18994. // Render targets
  18995. var i = this.customRenderTargets.length;
  18996. while (--i >= 0) {
  18997. this.customRenderTargets[i].dispose();
  18998. }
  18999. this.customRenderTargets = [];
  19000. // Active Meshes
  19001. this._activeMeshes.dispose();
  19002. _super.prototype.dispose.call(this);
  19003. };
  19004. Object.defineProperty(Camera.prototype, "leftCamera", {
  19005. // ---- Camera rigs section ----
  19006. get: function () {
  19007. if (this._rigCameras.length < 1) {
  19008. return null;
  19009. }
  19010. return this._rigCameras[0];
  19011. },
  19012. enumerable: true,
  19013. configurable: true
  19014. });
  19015. Object.defineProperty(Camera.prototype, "rightCamera", {
  19016. get: function () {
  19017. if (this._rigCameras.length < 2) {
  19018. return null;
  19019. }
  19020. return this._rigCameras[1];
  19021. },
  19022. enumerable: true,
  19023. configurable: true
  19024. });
  19025. Camera.prototype.getLeftTarget = function () {
  19026. if (this._rigCameras.length < 1) {
  19027. return null;
  19028. }
  19029. return this._rigCameras[0].getTarget();
  19030. };
  19031. Camera.prototype.getRightTarget = function () {
  19032. if (this._rigCameras.length < 2) {
  19033. return null;
  19034. }
  19035. return this._rigCameras[1].getTarget();
  19036. };
  19037. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19038. if (this.cameraRigMode === mode) {
  19039. return;
  19040. }
  19041. while (this._rigCameras.length > 0) {
  19042. var camera = this._rigCameras.pop();
  19043. if (camera) {
  19044. camera.dispose();
  19045. }
  19046. }
  19047. this.cameraRigMode = mode;
  19048. this._cameraRigParams = {};
  19049. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19050. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19051. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19052. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19053. // create the rig cameras, unless none
  19054. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19055. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19056. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19057. if (leftCamera && rightCamera) {
  19058. this._rigCameras.push(leftCamera);
  19059. this._rigCameras.push(rightCamera);
  19060. }
  19061. }
  19062. switch (this.cameraRigMode) {
  19063. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19064. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19065. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19066. break;
  19067. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19068. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19069. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19070. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19071. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19072. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19073. break;
  19074. case Camera.RIG_MODE_VR:
  19075. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19076. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19077. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19078. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19079. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19080. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19081. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19082. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19083. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19084. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19085. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19086. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19087. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19088. if (metrics.compensateDistortion) {
  19089. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19090. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19091. }
  19092. break;
  19093. case Camera.RIG_MODE_WEBVR:
  19094. if (rigParams.vrDisplay) {
  19095. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19096. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19097. //Left eye
  19098. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19099. this._rigCameras[0].setCameraRigParameter("left", true);
  19100. //leaving this for future reference
  19101. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19102. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19103. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19104. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19105. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19106. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19107. this._rigCameras[0].parent = this;
  19108. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19109. //Right eye
  19110. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19111. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19112. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19113. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19114. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19115. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19116. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19117. this._rigCameras[1].parent = this;
  19118. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19119. if (Camera.UseAlternateWebVRRendering) {
  19120. this._rigCameras[1]._skipRendering = true;
  19121. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19122. }
  19123. }
  19124. break;
  19125. }
  19126. this._cascadePostProcessesToRigCams();
  19127. this.update();
  19128. };
  19129. Camera.prototype._getVRProjectionMatrix = function () {
  19130. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19131. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19132. return this._projectionMatrix;
  19133. };
  19134. Camera.prototype._updateCameraRotationMatrix = function () {
  19135. //Here for WebVR
  19136. };
  19137. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19138. //Here for WebVR
  19139. };
  19140. /**
  19141. * This function MUST be overwritten by the different WebVR cameras available.
  19142. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19143. */
  19144. Camera.prototype._getWebVRProjectionMatrix = function () {
  19145. return BABYLON.Matrix.Identity();
  19146. };
  19147. /**
  19148. * This function MUST be overwritten by the different WebVR cameras available.
  19149. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19150. */
  19151. Camera.prototype._getWebVRViewMatrix = function () {
  19152. return BABYLON.Matrix.Identity();
  19153. };
  19154. Camera.prototype.setCameraRigParameter = function (name, value) {
  19155. if (!this._cameraRigParams) {
  19156. this._cameraRigParams = {};
  19157. }
  19158. this._cameraRigParams[name] = value;
  19159. //provisionnally:
  19160. if (name === "interaxialDistance") {
  19161. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19162. }
  19163. };
  19164. /**
  19165. * needs to be overridden by children so sub has required properties to be copied
  19166. */
  19167. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19168. return null;
  19169. };
  19170. /**
  19171. * May need to be overridden by children
  19172. */
  19173. Camera.prototype._updateRigCameras = function () {
  19174. for (var i = 0; i < this._rigCameras.length; i++) {
  19175. this._rigCameras[i].minZ = this.minZ;
  19176. this._rigCameras[i].maxZ = this.maxZ;
  19177. this._rigCameras[i].fov = this.fov;
  19178. }
  19179. // only update viewport when ANAGLYPH
  19180. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19181. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19182. }
  19183. };
  19184. Camera.prototype._setupInputs = function () {
  19185. };
  19186. Camera.prototype.serialize = function () {
  19187. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19188. // Type
  19189. serializationObject.type = this.getClassName();
  19190. // Parent
  19191. if (this.parent) {
  19192. serializationObject.parentId = this.parent.id;
  19193. }
  19194. if (this.inputs) {
  19195. this.inputs.serialize(serializationObject);
  19196. }
  19197. // Animations
  19198. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19199. serializationObject.ranges = this.serializeAnimationRanges();
  19200. return serializationObject;
  19201. };
  19202. Camera.prototype.clone = function (name) {
  19203. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19204. };
  19205. Camera.prototype.getDirection = function (localAxis) {
  19206. var result = BABYLON.Vector3.Zero();
  19207. this.getDirectionToRef(localAxis, result);
  19208. return result;
  19209. };
  19210. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19211. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19212. };
  19213. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19214. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19215. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19216. switch (type) {
  19217. case "ArcRotateCamera":
  19218. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19219. case "DeviceOrientationCamera":
  19220. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19221. case "FollowCamera":
  19222. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19223. case "ArcFollowCamera":
  19224. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19225. case "GamepadCamera":
  19226. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19227. case "TouchCamera":
  19228. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19229. case "VirtualJoysticksCamera":
  19230. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19231. case "WebVRFreeCamera":
  19232. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19233. case "WebVRGamepadCamera":
  19234. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19235. case "VRDeviceOrientationFreeCamera":
  19236. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19237. case "VRDeviceOrientationGamepadCamera":
  19238. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19239. case "AnaglyphArcRotateCamera":
  19240. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19241. case "AnaglyphFreeCamera":
  19242. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19243. case "AnaglyphGamepadCamera":
  19244. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19245. case "AnaglyphUniversalCamera":
  19246. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19247. case "StereoscopicArcRotateCamera":
  19248. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19249. case "StereoscopicFreeCamera":
  19250. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19251. case "StereoscopicGamepadCamera":
  19252. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19253. case "StereoscopicUniversalCamera":
  19254. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19255. case "FreeCamera":// Forcing Universal here
  19256. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19257. default:// Universal Camera is the default value
  19258. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19259. }
  19260. };
  19261. Camera.prototype.computeWorldMatrix = function () {
  19262. return this.getWorldMatrix();
  19263. };
  19264. Camera.Parse = function (parsedCamera, scene) {
  19265. var type = parsedCamera.type;
  19266. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19267. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19268. // Parent
  19269. if (parsedCamera.parentId) {
  19270. camera._waitingParentId = parsedCamera.parentId;
  19271. }
  19272. //If camera has an input manager, let it parse inputs settings
  19273. if (camera.inputs) {
  19274. camera.inputs.parse(parsedCamera);
  19275. camera._setupInputs();
  19276. }
  19277. if (camera.setPosition) {
  19278. camera.position.copyFromFloats(0, 0, 0);
  19279. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19280. }
  19281. // Target
  19282. if (parsedCamera.target) {
  19283. if (camera.setTarget) {
  19284. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19285. }
  19286. }
  19287. // Apply 3d rig, when found
  19288. if (parsedCamera.cameraRigMode) {
  19289. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19290. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19291. }
  19292. // Animations
  19293. if (parsedCamera.animations) {
  19294. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19295. var parsedAnimation = parsedCamera.animations[animationIndex];
  19296. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19297. }
  19298. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19299. }
  19300. if (parsedCamera.autoAnimate) {
  19301. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19302. }
  19303. return camera;
  19304. };
  19305. // Statics
  19306. Camera._PERSPECTIVE_CAMERA = 0;
  19307. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19308. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19309. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19310. Camera._RIG_MODE_NONE = 0;
  19311. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19312. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19313. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19314. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19315. Camera._RIG_MODE_VR = 20;
  19316. Camera._RIG_MODE_WEBVR = 21;
  19317. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19318. Camera.UseAlternateWebVRRendering = false;
  19319. __decorate([
  19320. BABYLON.serializeAsVector3()
  19321. ], Camera.prototype, "position", void 0);
  19322. __decorate([
  19323. BABYLON.serializeAsVector3()
  19324. ], Camera.prototype, "upVector", void 0);
  19325. __decorate([
  19326. BABYLON.serialize()
  19327. ], Camera.prototype, "orthoLeft", void 0);
  19328. __decorate([
  19329. BABYLON.serialize()
  19330. ], Camera.prototype, "orthoRight", void 0);
  19331. __decorate([
  19332. BABYLON.serialize()
  19333. ], Camera.prototype, "orthoBottom", void 0);
  19334. __decorate([
  19335. BABYLON.serialize()
  19336. ], Camera.prototype, "orthoTop", void 0);
  19337. __decorate([
  19338. BABYLON.serialize()
  19339. ], Camera.prototype, "fov", void 0);
  19340. __decorate([
  19341. BABYLON.serialize()
  19342. ], Camera.prototype, "minZ", void 0);
  19343. __decorate([
  19344. BABYLON.serialize()
  19345. ], Camera.prototype, "maxZ", void 0);
  19346. __decorate([
  19347. BABYLON.serialize()
  19348. ], Camera.prototype, "inertia", void 0);
  19349. __decorate([
  19350. BABYLON.serialize()
  19351. ], Camera.prototype, "mode", void 0);
  19352. __decorate([
  19353. BABYLON.serialize()
  19354. ], Camera.prototype, "layerMask", void 0);
  19355. __decorate([
  19356. BABYLON.serialize()
  19357. ], Camera.prototype, "fovMode", void 0);
  19358. __decorate([
  19359. BABYLON.serialize()
  19360. ], Camera.prototype, "cameraRigMode", void 0);
  19361. __decorate([
  19362. BABYLON.serialize()
  19363. ], Camera.prototype, "interaxialDistance", void 0);
  19364. __decorate([
  19365. BABYLON.serialize()
  19366. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19367. return Camera;
  19368. }(BABYLON.Node));
  19369. BABYLON.Camera = Camera;
  19370. })(BABYLON || (BABYLON = {}));
  19371. //# sourceMappingURL=babylon.camera.js.map
  19372. var BABYLON;
  19373. (function (BABYLON) {
  19374. var RenderingManager = /** @class */ (function () {
  19375. function RenderingManager(scene) {
  19376. this._renderingGroups = new Array();
  19377. this._autoClearDepthStencil = {};
  19378. this._customOpaqueSortCompareFn = {};
  19379. this._customAlphaTestSortCompareFn = {};
  19380. this._customTransparentSortCompareFn = {};
  19381. this._renderinGroupInfo = null;
  19382. this._scene = scene;
  19383. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19384. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19385. }
  19386. }
  19387. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19388. if (depth === void 0) { depth = true; }
  19389. if (stencil === void 0) { stencil = true; }
  19390. if (this._depthStencilBufferAlreadyCleaned) {
  19391. return;
  19392. }
  19393. this._scene.getEngine().clear(null, false, depth, stencil);
  19394. this._depthStencilBufferAlreadyCleaned = true;
  19395. };
  19396. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19397. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19398. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19399. var info = null;
  19400. if (observable) {
  19401. if (!this._renderinGroupInfo) {
  19402. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19403. }
  19404. info = this._renderinGroupInfo;
  19405. info.scene = this._scene;
  19406. info.camera = this._scene.activeCamera;
  19407. }
  19408. // Dispatch sprites
  19409. if (renderSprites) {
  19410. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19411. var manager = this._scene.spriteManagers[index];
  19412. this.dispatchSprites(manager);
  19413. }
  19414. }
  19415. // Render
  19416. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19417. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19418. var renderingGroup = this._renderingGroups[index];
  19419. if (!renderingGroup && !observable)
  19420. continue;
  19421. var renderingGroupMask = 0;
  19422. // Fire PRECLEAR stage
  19423. if (observable && info) {
  19424. renderingGroupMask = Math.pow(2, index);
  19425. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19426. info.renderingGroupId = index;
  19427. observable.notifyObservers(info, renderingGroupMask);
  19428. }
  19429. // Clear depth/stencil if needed
  19430. if (RenderingManager.AUTOCLEAR) {
  19431. var autoClear = this._autoClearDepthStencil[index];
  19432. if (autoClear && autoClear.autoClear) {
  19433. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19434. }
  19435. }
  19436. if (observable && info) {
  19437. // Fire PREOPAQUE stage
  19438. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19439. observable.notifyObservers(info, renderingGroupMask);
  19440. // Fire PRETRANSPARENT stage
  19441. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19442. observable.notifyObservers(info, renderingGroupMask);
  19443. }
  19444. if (renderingGroup)
  19445. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19446. // Fire POSTTRANSPARENT stage
  19447. if (observable && info) {
  19448. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19449. observable.notifyObservers(info, renderingGroupMask);
  19450. }
  19451. }
  19452. };
  19453. RenderingManager.prototype.reset = function () {
  19454. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19455. var renderingGroup = this._renderingGroups[index];
  19456. if (renderingGroup) {
  19457. renderingGroup.prepare();
  19458. }
  19459. }
  19460. };
  19461. RenderingManager.prototype.dispose = function () {
  19462. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19463. var renderingGroup = this._renderingGroups[index];
  19464. if (renderingGroup) {
  19465. renderingGroup.dispose();
  19466. }
  19467. }
  19468. this._renderingGroups.length = 0;
  19469. };
  19470. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19471. if (this._renderingGroups[renderingGroupId] === undefined) {
  19472. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19473. }
  19474. };
  19475. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19476. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19477. this._prepareRenderingGroup(renderingGroupId);
  19478. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19479. };
  19480. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19481. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19482. this._prepareRenderingGroup(renderingGroupId);
  19483. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19484. };
  19485. /**
  19486. * @param subMesh The submesh to dispatch
  19487. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19488. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19489. */
  19490. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19491. if (mesh === undefined) {
  19492. mesh = subMesh.getMesh();
  19493. }
  19494. var renderingGroupId = mesh.renderingGroupId || 0;
  19495. this._prepareRenderingGroup(renderingGroupId);
  19496. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19497. };
  19498. /**
  19499. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19500. * This allowed control for front to back rendering or reversly depending of the special needs.
  19501. *
  19502. * @param renderingGroupId The rendering group id corresponding to its index
  19503. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19504. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19505. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19506. */
  19507. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19508. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19509. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19510. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19511. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19512. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19513. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19514. if (this._renderingGroups[renderingGroupId]) {
  19515. var group = this._renderingGroups[renderingGroupId];
  19516. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19517. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19518. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19519. }
  19520. };
  19521. /**
  19522. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19523. *
  19524. * @param renderingGroupId The rendering group id corresponding to its index
  19525. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19526. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19527. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19528. */
  19529. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19530. if (depth === void 0) { depth = true; }
  19531. if (stencil === void 0) { stencil = true; }
  19532. this._autoClearDepthStencil[renderingGroupId] = {
  19533. autoClear: autoClearDepthStencil,
  19534. depth: depth,
  19535. stencil: stencil
  19536. };
  19537. };
  19538. /**
  19539. * The max id used for rendering groups (not included)
  19540. */
  19541. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19542. /**
  19543. * The min id used for rendering groups (included)
  19544. */
  19545. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19546. /**
  19547. * Used to globally prevent autoclearing scenes.
  19548. */
  19549. RenderingManager.AUTOCLEAR = true;
  19550. return RenderingManager;
  19551. }());
  19552. BABYLON.RenderingManager = RenderingManager;
  19553. })(BABYLON || (BABYLON = {}));
  19554. //# sourceMappingURL=babylon.renderingManager.js.map
  19555. var BABYLON;
  19556. (function (BABYLON) {
  19557. var RenderingGroup = /** @class */ (function () {
  19558. /**
  19559. * Creates a new rendering group.
  19560. * @param index The rendering group index
  19561. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19562. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19563. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19564. */
  19565. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19566. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19567. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19568. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19569. this.index = index;
  19570. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19571. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19572. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19573. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19574. this._particleSystems = new BABYLON.SmartArray(256);
  19575. this._spriteManagers = new BABYLON.SmartArray(256);
  19576. this._edgesRenderers = new BABYLON.SmartArray(16);
  19577. this._scene = scene;
  19578. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19579. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19580. this.transparentSortCompareFn = transparentSortCompareFn;
  19581. }
  19582. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19583. /**
  19584. * Set the opaque sort comparison function.
  19585. * If null the sub meshes will be render in the order they were created
  19586. */
  19587. set: function (value) {
  19588. this._opaqueSortCompareFn = value;
  19589. if (value) {
  19590. this._renderOpaque = this.renderOpaqueSorted;
  19591. }
  19592. else {
  19593. this._renderOpaque = RenderingGroup.renderUnsorted;
  19594. }
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19600. /**
  19601. * Set the alpha test sort comparison function.
  19602. * If null the sub meshes will be render in the order they were created
  19603. */
  19604. set: function (value) {
  19605. this._alphaTestSortCompareFn = value;
  19606. if (value) {
  19607. this._renderAlphaTest = this.renderAlphaTestSorted;
  19608. }
  19609. else {
  19610. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19611. }
  19612. },
  19613. enumerable: true,
  19614. configurable: true
  19615. });
  19616. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19617. /**
  19618. * Set the transparent sort comparison function.
  19619. * If null the sub meshes will be render in the order they were created
  19620. */
  19621. set: function (value) {
  19622. if (value) {
  19623. this._transparentSortCompareFn = value;
  19624. }
  19625. else {
  19626. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19627. }
  19628. this._renderTransparent = this.renderTransparentSorted;
  19629. },
  19630. enumerable: true,
  19631. configurable: true
  19632. });
  19633. /**
  19634. * Render all the sub meshes contained in the group.
  19635. * @param customRenderFunction Used to override the default render behaviour of the group.
  19636. * @returns true if rendered some submeshes.
  19637. */
  19638. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19639. if (customRenderFunction) {
  19640. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19641. return;
  19642. }
  19643. var engine = this._scene.getEngine();
  19644. // Depth only
  19645. if (this._depthOnlySubMeshes.length !== 0) {
  19646. engine.setColorWrite(false);
  19647. this._renderAlphaTest(this._depthOnlySubMeshes);
  19648. engine.setColorWrite(true);
  19649. }
  19650. // Opaque
  19651. if (this._opaqueSubMeshes.length !== 0) {
  19652. this._renderOpaque(this._opaqueSubMeshes);
  19653. }
  19654. // Alpha test
  19655. if (this._alphaTestSubMeshes.length !== 0) {
  19656. this._renderAlphaTest(this._alphaTestSubMeshes);
  19657. }
  19658. var stencilState = engine.getStencilBuffer();
  19659. engine.setStencilBuffer(false);
  19660. // Sprites
  19661. if (renderSprites) {
  19662. this._renderSprites();
  19663. }
  19664. // Particles
  19665. if (renderParticles) {
  19666. this._renderParticles(activeMeshes);
  19667. }
  19668. if (this.onBeforeTransparentRendering) {
  19669. this.onBeforeTransparentRendering();
  19670. }
  19671. // Transparent
  19672. if (this._transparentSubMeshes.length !== 0) {
  19673. this._renderTransparent(this._transparentSubMeshes);
  19674. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19675. }
  19676. // Set back stencil to false in case it changes before the edge renderer.
  19677. engine.setStencilBuffer(false);
  19678. // Edges
  19679. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19680. this._edgesRenderers.data[edgesRendererIndex].render();
  19681. }
  19682. // Restore Stencil state.
  19683. engine.setStencilBuffer(stencilState);
  19684. };
  19685. /**
  19686. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19687. * @param subMeshes The submeshes to render
  19688. */
  19689. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19690. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19691. };
  19692. /**
  19693. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19694. * @param subMeshes The submeshes to render
  19695. */
  19696. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19697. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19698. };
  19699. /**
  19700. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19701. * @param subMeshes The submeshes to render
  19702. */
  19703. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19704. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19705. };
  19706. /**
  19707. * Renders the submeshes in a specified order.
  19708. * @param subMeshes The submeshes to sort before render
  19709. * @param sortCompareFn The comparison function use to sort
  19710. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19711. * @param transparent Specifies to activate blending if true
  19712. */
  19713. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19714. var subIndex = 0;
  19715. var subMesh;
  19716. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19717. for (; subIndex < subMeshes.length; subIndex++) {
  19718. subMesh = subMeshes.data[subIndex];
  19719. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19720. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19721. }
  19722. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19723. if (sortCompareFn) {
  19724. sortedArray.sort(sortCompareFn);
  19725. }
  19726. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19727. subMesh = sortedArray[subIndex];
  19728. if (transparent) {
  19729. var material = subMesh.getMaterial();
  19730. if (material && material.needDepthPrePass) {
  19731. var engine = material.getScene().getEngine();
  19732. engine.setColorWrite(false);
  19733. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19734. subMesh.render(false);
  19735. engine.setColorWrite(true);
  19736. }
  19737. }
  19738. subMesh.render(transparent);
  19739. }
  19740. };
  19741. /**
  19742. * Renders the submeshes in the order they were dispatched (no sort applied).
  19743. * @param subMeshes The submeshes to render
  19744. */
  19745. RenderingGroup.renderUnsorted = function (subMeshes) {
  19746. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19747. var submesh = subMeshes.data[subIndex];
  19748. submesh.render(false);
  19749. }
  19750. };
  19751. /**
  19752. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19753. * are rendered back to front if in the same alpha index.
  19754. *
  19755. * @param a The first submesh
  19756. * @param b The second submesh
  19757. * @returns The result of the comparison
  19758. */
  19759. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19760. // Alpha index first
  19761. if (a._alphaIndex > b._alphaIndex) {
  19762. return 1;
  19763. }
  19764. if (a._alphaIndex < b._alphaIndex) {
  19765. return -1;
  19766. }
  19767. // Then distance to camera
  19768. return RenderingGroup.backToFrontSortCompare(a, b);
  19769. };
  19770. /**
  19771. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19772. * are rendered back to front.
  19773. *
  19774. * @param a The first submesh
  19775. * @param b The second submesh
  19776. * @returns The result of the comparison
  19777. */
  19778. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19779. // Then distance to camera
  19780. if (a._distanceToCamera < b._distanceToCamera) {
  19781. return 1;
  19782. }
  19783. if (a._distanceToCamera > b._distanceToCamera) {
  19784. return -1;
  19785. }
  19786. return 0;
  19787. };
  19788. /**
  19789. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19790. * are rendered front to back (prevent overdraw).
  19791. *
  19792. * @param a The first submesh
  19793. * @param b The second submesh
  19794. * @returns The result of the comparison
  19795. */
  19796. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19797. // Then distance to camera
  19798. if (a._distanceToCamera < b._distanceToCamera) {
  19799. return -1;
  19800. }
  19801. if (a._distanceToCamera > b._distanceToCamera) {
  19802. return 1;
  19803. }
  19804. return 0;
  19805. };
  19806. /**
  19807. * Resets the different lists of submeshes to prepare a new frame.
  19808. */
  19809. RenderingGroup.prototype.prepare = function () {
  19810. this._opaqueSubMeshes.reset();
  19811. this._transparentSubMeshes.reset();
  19812. this._alphaTestSubMeshes.reset();
  19813. this._depthOnlySubMeshes.reset();
  19814. this._particleSystems.reset();
  19815. this._spriteManagers.reset();
  19816. this._edgesRenderers.reset();
  19817. };
  19818. RenderingGroup.prototype.dispose = function () {
  19819. this._opaqueSubMeshes.dispose();
  19820. this._transparentSubMeshes.dispose();
  19821. this._alphaTestSubMeshes.dispose();
  19822. this._depthOnlySubMeshes.dispose();
  19823. this._particleSystems.dispose();
  19824. this._spriteManagers.dispose();
  19825. this._edgesRenderers.dispose();
  19826. };
  19827. /**
  19828. * Inserts the submesh in its correct queue depending on its material.
  19829. * @param subMesh The submesh to dispatch
  19830. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19831. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19832. */
  19833. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19834. // Get mesh and materials if not provided
  19835. if (mesh === undefined) {
  19836. mesh = subMesh.getMesh();
  19837. }
  19838. if (material === undefined) {
  19839. material = subMesh.getMaterial();
  19840. }
  19841. if (material === null || material === undefined) {
  19842. return;
  19843. }
  19844. if (material.needAlphaBlendingForMesh(mesh)) {
  19845. this._transparentSubMeshes.push(subMesh);
  19846. }
  19847. else if (material.needAlphaTesting()) {
  19848. if (material.needDepthPrePass) {
  19849. this._depthOnlySubMeshes.push(subMesh);
  19850. }
  19851. this._alphaTestSubMeshes.push(subMesh);
  19852. }
  19853. else {
  19854. if (material.needDepthPrePass) {
  19855. this._depthOnlySubMeshes.push(subMesh);
  19856. }
  19857. this._opaqueSubMeshes.push(subMesh); // Opaque
  19858. }
  19859. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19860. this._edgesRenderers.push(mesh._edgesRenderer);
  19861. }
  19862. };
  19863. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19864. this._spriteManagers.push(spriteManager);
  19865. };
  19866. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19867. this._particleSystems.push(particleSystem);
  19868. };
  19869. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19870. if (this._particleSystems.length === 0) {
  19871. return;
  19872. }
  19873. // Particles
  19874. var activeCamera = this._scene.activeCamera;
  19875. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19876. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19877. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19878. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19879. continue;
  19880. }
  19881. var emitter = particleSystem.emitter;
  19882. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19883. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19884. }
  19885. }
  19886. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19887. };
  19888. RenderingGroup.prototype._renderSprites = function () {
  19889. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19890. return;
  19891. }
  19892. // Sprites
  19893. var activeCamera = this._scene.activeCamera;
  19894. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19895. for (var id = 0; id < this._spriteManagers.length; id++) {
  19896. var spriteManager = this._spriteManagers.data[id];
  19897. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19898. spriteManager.render();
  19899. }
  19900. }
  19901. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19902. };
  19903. return RenderingGroup;
  19904. }());
  19905. BABYLON.RenderingGroup = RenderingGroup;
  19906. })(BABYLON || (BABYLON = {}));
  19907. //# sourceMappingURL=babylon.renderingGroup.js.map
  19908. var BABYLON;
  19909. (function (BABYLON) {
  19910. var ClickInfo = /** @class */ (function () {
  19911. function ClickInfo() {
  19912. this._singleClick = false;
  19913. this._doubleClick = false;
  19914. this._hasSwiped = false;
  19915. this._ignore = false;
  19916. }
  19917. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19918. get: function () {
  19919. return this._singleClick;
  19920. },
  19921. set: function (b) {
  19922. this._singleClick = b;
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19928. get: function () {
  19929. return this._doubleClick;
  19930. },
  19931. set: function (b) {
  19932. this._doubleClick = b;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19938. get: function () {
  19939. return this._hasSwiped;
  19940. },
  19941. set: function (b) {
  19942. this._hasSwiped = b;
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19948. get: function () {
  19949. return this._ignore;
  19950. },
  19951. set: function (b) {
  19952. this._ignore = b;
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. return ClickInfo;
  19958. }());
  19959. /**
  19960. * This class is used by the onRenderingGroupObservable
  19961. */
  19962. var RenderingGroupInfo = /** @class */ (function () {
  19963. function RenderingGroupInfo() {
  19964. }
  19965. /**
  19966. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19967. * This stage will be fired no matter what
  19968. */
  19969. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19970. /**
  19971. * Called before opaque object are rendered.
  19972. * This stage will be fired only if there's 3D Opaque content to render
  19973. */
  19974. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19975. /**
  19976. * Called after the opaque objects are rendered and before the transparent ones
  19977. * This stage will be fired only if there's 3D transparent content to render
  19978. */
  19979. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19980. /**
  19981. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19982. * This stage will be fired no matter what
  19983. */
  19984. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19985. return RenderingGroupInfo;
  19986. }());
  19987. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19988. /**
  19989. * Represents a scene to be rendered by the engine.
  19990. * @see http://doc.babylonjs.com/page.php?p=21911
  19991. */
  19992. var Scene = /** @class */ (function () {
  19993. /**
  19994. * @constructor
  19995. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19996. */
  19997. function Scene(engine) {
  19998. // Members
  19999. this.autoClear = true;
  20000. this.autoClearDepthAndStencil = true;
  20001. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20002. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20003. this.forceWireframe = false;
  20004. this._forcePointsCloud = false;
  20005. this.forceShowBoundingBoxes = false;
  20006. this.animationsEnabled = true;
  20007. this.useConstantAnimationDeltaTime = false;
  20008. this.constantlyUpdateMeshUnderPointer = false;
  20009. this.hoverCursor = "pointer";
  20010. this.defaultCursor = "";
  20011. /**
  20012. * This is used to call preventDefault() on pointer down
  20013. * in order to block unwanted artifacts like system double clicks
  20014. */
  20015. this.preventDefaultOnPointerDown = true;
  20016. // Metadata
  20017. this.metadata = null;
  20018. /**
  20019. * An event triggered when the scene is disposed.
  20020. * @type {BABYLON.Observable}
  20021. */
  20022. this.onDisposeObservable = new BABYLON.Observable();
  20023. /**
  20024. * An event triggered before rendering the scene (right after animations and physics)
  20025. * @type {BABYLON.Observable}
  20026. */
  20027. this.onBeforeRenderObservable = new BABYLON.Observable();
  20028. /**
  20029. * An event triggered after rendering the scene
  20030. * @type {BABYLON.Observable}
  20031. */
  20032. this.onAfterRenderObservable = new BABYLON.Observable();
  20033. /**
  20034. * An event triggered before animating the scene
  20035. * @type {BABYLON.Observable}
  20036. */
  20037. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20038. /**
  20039. * An event triggered after animations processing
  20040. * @type {BABYLON.Observable}
  20041. */
  20042. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20043. /**
  20044. * An event triggered before draw calls are ready to be sent
  20045. * @type {BABYLON.Observable}
  20046. */
  20047. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20048. /**
  20049. * An event triggered after draw calls have been sent
  20050. * @type {BABYLON.Observable}
  20051. */
  20052. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20053. /**
  20054. * An event triggered when physic simulation is about to be run
  20055. * @type {BABYLON.Observable}
  20056. */
  20057. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20058. /**
  20059. * An event triggered when physic simulation has been done
  20060. * @type {BABYLON.Observable}
  20061. */
  20062. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20063. /**
  20064. * An event triggered when the scene is ready
  20065. * @type {BABYLON.Observable}
  20066. */
  20067. this.onReadyObservable = new BABYLON.Observable();
  20068. /**
  20069. * An event triggered before rendering a camera
  20070. * @type {BABYLON.Observable}
  20071. */
  20072. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20073. /**
  20074. * An event triggered after rendering a camera
  20075. * @type {BABYLON.Observable}
  20076. */
  20077. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20078. /**
  20079. * An event triggered when active meshes evaluation is about to start
  20080. * @type {BABYLON.Observable}
  20081. */
  20082. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20083. /**
  20084. * An event triggered when active meshes evaluation is done
  20085. * @type {BABYLON.Observable}
  20086. */
  20087. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20088. /**
  20089. * An event triggered when particles rendering is about to start
  20090. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20091. * @type {BABYLON.Observable}
  20092. */
  20093. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20094. /**
  20095. * An event triggered when particles rendering is done
  20096. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20097. * @type {BABYLON.Observable}
  20098. */
  20099. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20100. /**
  20101. * An event triggered when sprites rendering is about to start
  20102. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20103. * @type {BABYLON.Observable}
  20104. */
  20105. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20106. /**
  20107. * An event triggered when sprites rendering is done
  20108. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20109. * @type {BABYLON.Observable}
  20110. */
  20111. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20112. /**
  20113. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20114. * @type {BABYLON.Observable}
  20115. */
  20116. this.onDataLoadedObservable = new BABYLON.Observable();
  20117. /**
  20118. * An event triggered when a camera is created
  20119. * @type {BABYLON.Observable}
  20120. */
  20121. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20122. /**
  20123. * An event triggered when a camera is removed
  20124. * @type {BABYLON.Observable}
  20125. */
  20126. this.onCameraRemovedObservable = new BABYLON.Observable();
  20127. /**
  20128. * An event triggered when a light is created
  20129. * @type {BABYLON.Observable}
  20130. */
  20131. this.onNewLightAddedObservable = new BABYLON.Observable();
  20132. /**
  20133. * An event triggered when a light is removed
  20134. * @type {BABYLON.Observable}
  20135. */
  20136. this.onLightRemovedObservable = new BABYLON.Observable();
  20137. /**
  20138. * An event triggered when a geometry is created
  20139. * @type {BABYLON.Observable}
  20140. */
  20141. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20142. /**
  20143. * An event triggered when a geometry is removed
  20144. * @type {BABYLON.Observable}
  20145. */
  20146. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20147. /**
  20148. * An event triggered when a transform node is created
  20149. * @type {BABYLON.Observable}
  20150. */
  20151. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20152. /**
  20153. * An event triggered when a transform node is removed
  20154. * @type {BABYLON.Observable}
  20155. */
  20156. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20157. /**
  20158. * An event triggered when a mesh is created
  20159. * @type {BABYLON.Observable}
  20160. */
  20161. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20162. /**
  20163. * An event triggered when a mesh is removed
  20164. * @type {BABYLON.Observable}
  20165. */
  20166. this.onMeshRemovedObservable = new BABYLON.Observable();
  20167. /**
  20168. * An event triggered when render targets are about to be rendered
  20169. * Can happen multiple times per frame.
  20170. * @type {BABYLON.Observable}
  20171. */
  20172. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20173. /**
  20174. * An event triggered when render targets were rendered.
  20175. * Can happen multiple times per frame.
  20176. * @type {BABYLON.Observable}
  20177. */
  20178. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20179. /**
  20180. * An event triggered before calculating deterministic simulation step
  20181. * @type {BABYLON.Observable}
  20182. */
  20183. this.onBeforeStepObservable = new BABYLON.Observable();
  20184. /**
  20185. * An event triggered after calculating deterministic simulation step
  20186. * @type {BABYLON.Observable}
  20187. */
  20188. this.onAfterStepObservable = new BABYLON.Observable();
  20189. /**
  20190. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20191. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20192. * 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)
  20193. */
  20194. this.onRenderingGroupObservable = new BABYLON.Observable();
  20195. // Animations
  20196. this.animations = [];
  20197. /**
  20198. * 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).
  20199. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20200. */
  20201. this.onPrePointerObservable = new BABYLON.Observable();
  20202. /**
  20203. * Observable event triggered each time an input event is received from the rendering canvas
  20204. */
  20205. this.onPointerObservable = new BABYLON.Observable();
  20206. this._meshPickProceed = false;
  20207. this._currentPickResult = null;
  20208. this._previousPickResult = null;
  20209. this._totalPointersPressed = 0;
  20210. this._doubleClickOccured = false;
  20211. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20212. this.cameraToUseForPointers = null;
  20213. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20214. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20215. this._startingPointerTime = 0;
  20216. this._previousStartingPointerTime = 0;
  20217. // Deterministic lockstep
  20218. this._timeAccumulator = 0;
  20219. this._currentStepId = 0;
  20220. this._currentInternalStep = 0;
  20221. // Keyboard
  20222. /**
  20223. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20224. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20225. */
  20226. this.onPreKeyboardObservable = new BABYLON.Observable();
  20227. /**
  20228. * Observable event triggered each time an keyboard event is received from the hosting window
  20229. */
  20230. this.onKeyboardObservable = new BABYLON.Observable();
  20231. // Coordinate system
  20232. /**
  20233. * use right-handed coordinate system on this scene.
  20234. * @type {boolean}
  20235. */
  20236. this._useRightHandedSystem = false;
  20237. // Fog
  20238. this._fogEnabled = true;
  20239. this._fogMode = Scene.FOGMODE_NONE;
  20240. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20241. this.fogDensity = 0.1;
  20242. this.fogStart = 0;
  20243. this.fogEnd = 1000.0;
  20244. // Lights
  20245. /**
  20246. * is shadow enabled on this scene.
  20247. * @type {boolean}
  20248. */
  20249. this._shadowsEnabled = true;
  20250. /**
  20251. * is light enabled on this scene.
  20252. * @type {boolean}
  20253. */
  20254. this._lightsEnabled = true;
  20255. /**
  20256. * All of the lights added to this scene.
  20257. * @see BABYLON.Light
  20258. * @type {BABYLON.Light[]}
  20259. */
  20260. this.lights = new Array();
  20261. // Cameras
  20262. /** All of the cameras added to this scene. */
  20263. this.cameras = new Array();
  20264. /** All of the active cameras added to this scene. */
  20265. this.activeCameras = new Array();
  20266. // Meshes
  20267. /**
  20268. * All of the tranform nodes added to this scene.
  20269. * @see BABYLON.TransformNode
  20270. * @type {BABYLON.TransformNode[]}
  20271. */
  20272. this.transformNodes = new Array();
  20273. /**
  20274. * All of the (abstract) meshes added to this scene.
  20275. * @see BABYLON.AbstractMesh
  20276. * @type {BABYLON.AbstractMesh[]}
  20277. */
  20278. this.meshes = new Array();
  20279. /**
  20280. * All of the animation groups added to this scene.
  20281. * @see BABYLON.AnimationGroup
  20282. * @type {BABYLON.AnimationGroup[]}
  20283. */
  20284. this.animationGroups = new Array();
  20285. // Geometries
  20286. this._geometries = new Array();
  20287. this.materials = new Array();
  20288. this.multiMaterials = new Array();
  20289. // Textures
  20290. this._texturesEnabled = true;
  20291. this.textures = new Array();
  20292. // Particles
  20293. this.particlesEnabled = true;
  20294. this.particleSystems = new Array();
  20295. // Sprites
  20296. this.spritesEnabled = true;
  20297. this.spriteManagers = new Array();
  20298. // Layers
  20299. this.layers = new Array();
  20300. this.highlightLayers = new Array();
  20301. // Skeletons
  20302. this._skeletonsEnabled = true;
  20303. this.skeletons = new Array();
  20304. // Morph targets
  20305. this.morphTargetManagers = new Array();
  20306. // Lens flares
  20307. this.lensFlaresEnabled = true;
  20308. this.lensFlareSystems = new Array();
  20309. // Collisions
  20310. this.collisionsEnabled = true;
  20311. /** Defines the gravity applied to this scene */
  20312. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20313. // Postprocesses
  20314. this.postProcesses = new Array();
  20315. this.postProcessesEnabled = true;
  20316. // Customs render targets
  20317. this.renderTargetsEnabled = true;
  20318. this.dumpNextRenderTargets = false;
  20319. this.customRenderTargets = new Array();
  20320. // Imported meshes
  20321. this.importedMeshesFiles = new Array();
  20322. // Probes
  20323. this.probesEnabled = true;
  20324. this.reflectionProbes = new Array();
  20325. this._actionManagers = new Array();
  20326. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20327. // Procedural textures
  20328. this.proceduralTexturesEnabled = true;
  20329. this._proceduralTextures = new Array();
  20330. this.soundTracks = new Array();
  20331. this._audioEnabled = true;
  20332. this._headphone = false;
  20333. // Performance counters
  20334. this._totalVertices = new BABYLON.PerfCounter();
  20335. this._activeIndices = new BABYLON.PerfCounter();
  20336. this._activeParticles = new BABYLON.PerfCounter();
  20337. this._activeBones = new BABYLON.PerfCounter();
  20338. this._animationTime = 0;
  20339. this.animationTimeScale = 1;
  20340. this._renderId = 0;
  20341. this._executeWhenReadyTimeoutId = -1;
  20342. this._intermediateRendering = false;
  20343. this._viewUpdateFlag = -1;
  20344. this._projectionUpdateFlag = -1;
  20345. this._alternateViewUpdateFlag = -1;
  20346. this._alternateProjectionUpdateFlag = -1;
  20347. this._toBeDisposed = new BABYLON.SmartArray(256);
  20348. this._activeRequests = new Array();
  20349. this._pendingData = new Array();
  20350. this._isDisposed = false;
  20351. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20352. this._activeMeshes = new BABYLON.SmartArray(256);
  20353. this._processedMaterials = new BABYLON.SmartArray(256);
  20354. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20355. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20356. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20357. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20358. this._activeAnimatables = new Array();
  20359. this._transformMatrix = BABYLON.Matrix.Zero();
  20360. this._useAlternateCameraConfiguration = false;
  20361. this._alternateRendering = false;
  20362. this.requireLightSorting = false;
  20363. this._activeMeshesFrozen = false;
  20364. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20365. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20366. this._engine.scenes.push(this);
  20367. this._uid = null;
  20368. this._renderingManager = new BABYLON.RenderingManager(this);
  20369. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20370. if (BABYLON.OutlineRenderer) {
  20371. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20372. }
  20373. if (BABYLON.Tools.IsWindowObjectExist()) {
  20374. this.attachControl();
  20375. }
  20376. //simplification queue
  20377. if (BABYLON.SimplificationQueue) {
  20378. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20379. }
  20380. //collision coordinator initialization. For now legacy per default.
  20381. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20382. // Uniform Buffer
  20383. this._createUbo();
  20384. // Default Image processing definition.
  20385. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20386. }
  20387. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20388. /** The fog is deactivated */
  20389. get: function () {
  20390. return Scene._FOGMODE_NONE;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20396. /** The fog density is following an exponential function */
  20397. get: function () {
  20398. return Scene._FOGMODE_EXP;
  20399. },
  20400. enumerable: true,
  20401. configurable: true
  20402. });
  20403. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20404. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20405. get: function () {
  20406. return Scene._FOGMODE_EXP2;
  20407. },
  20408. enumerable: true,
  20409. configurable: true
  20410. });
  20411. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20412. /** The fog density is following a linear function. */
  20413. get: function () {
  20414. return Scene._FOGMODE_LINEAR;
  20415. },
  20416. enumerable: true,
  20417. configurable: true
  20418. });
  20419. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20420. /**
  20421. * Texture used in all pbr material as the reflection texture.
  20422. * As in the majority of the scene they are the same (exception for multi room and so on),
  20423. * this is easier to reference from here than from all the materials.
  20424. */
  20425. get: function () {
  20426. return this._environmentTexture;
  20427. },
  20428. /**
  20429. * Texture used in all pbr material as the reflection texture.
  20430. * As in the majority of the scene they are the same (exception for multi room and so on),
  20431. * this is easier to set here than in all the materials.
  20432. */
  20433. set: function (value) {
  20434. if (this._environmentTexture === value) {
  20435. return;
  20436. }
  20437. this._environmentTexture = value;
  20438. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20439. },
  20440. enumerable: true,
  20441. configurable: true
  20442. });
  20443. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20444. /**
  20445. * Default image processing configuration used either in the rendering
  20446. * Forward main pass or through the imageProcessingPostProcess if present.
  20447. * As in the majority of the scene they are the same (exception for multi camera),
  20448. * this is easier to reference from here than from all the materials and post process.
  20449. *
  20450. * No setter as we it is a shared configuration, you can set the values instead.
  20451. */
  20452. get: function () {
  20453. return this._imageProcessingConfiguration;
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20459. get: function () {
  20460. return this._forcePointsCloud;
  20461. },
  20462. set: function (value) {
  20463. if (this._forcePointsCloud === value) {
  20464. return;
  20465. }
  20466. this._forcePointsCloud = value;
  20467. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20468. },
  20469. enumerable: true,
  20470. configurable: true
  20471. });
  20472. Object.defineProperty(Scene.prototype, "onDispose", {
  20473. /** A function to be executed when this scene is disposed. */
  20474. set: function (callback) {
  20475. if (this._onDisposeObserver) {
  20476. this.onDisposeObservable.remove(this._onDisposeObserver);
  20477. }
  20478. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20479. },
  20480. enumerable: true,
  20481. configurable: true
  20482. });
  20483. Object.defineProperty(Scene.prototype, "beforeRender", {
  20484. /** A function to be executed before rendering this scene */
  20485. set: function (callback) {
  20486. if (this._onBeforeRenderObserver) {
  20487. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20488. }
  20489. if (callback) {
  20490. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20491. }
  20492. },
  20493. enumerable: true,
  20494. configurable: true
  20495. });
  20496. Object.defineProperty(Scene.prototype, "afterRender", {
  20497. /** A function to be executed after rendering this scene */
  20498. set: function (callback) {
  20499. if (this._onAfterRenderObserver) {
  20500. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20501. }
  20502. if (callback) {
  20503. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20504. }
  20505. },
  20506. enumerable: true,
  20507. configurable: true
  20508. });
  20509. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20510. set: function (callback) {
  20511. if (this._onBeforeCameraRenderObserver) {
  20512. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20513. }
  20514. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20515. },
  20516. enumerable: true,
  20517. configurable: true
  20518. });
  20519. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20520. set: function (callback) {
  20521. if (this._onAfterCameraRenderObserver) {
  20522. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20523. }
  20524. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20525. },
  20526. enumerable: true,
  20527. configurable: true
  20528. });
  20529. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20530. get: function () {
  20531. if (!this._gamepadManager) {
  20532. this._gamepadManager = new BABYLON.GamepadManager(this);
  20533. }
  20534. return this._gamepadManager;
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20540. get: function () {
  20541. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20547. get: function () {
  20548. return this._useRightHandedSystem;
  20549. },
  20550. set: function (value) {
  20551. if (this._useRightHandedSystem === value) {
  20552. return;
  20553. }
  20554. this._useRightHandedSystem = value;
  20555. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20556. },
  20557. enumerable: true,
  20558. configurable: true
  20559. });
  20560. Scene.prototype.setStepId = function (newStepId) {
  20561. this._currentStepId = newStepId;
  20562. };
  20563. ;
  20564. Scene.prototype.getStepId = function () {
  20565. return this._currentStepId;
  20566. };
  20567. ;
  20568. Scene.prototype.getInternalStep = function () {
  20569. return this._currentInternalStep;
  20570. };
  20571. ;
  20572. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20573. get: function () {
  20574. return this._fogEnabled;
  20575. },
  20576. /**
  20577. * is fog enabled on this scene.
  20578. */
  20579. set: function (value) {
  20580. if (this._fogEnabled === value) {
  20581. return;
  20582. }
  20583. this._fogEnabled = value;
  20584. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20585. },
  20586. enumerable: true,
  20587. configurable: true
  20588. });
  20589. Object.defineProperty(Scene.prototype, "fogMode", {
  20590. get: function () {
  20591. return this._fogMode;
  20592. },
  20593. set: function (value) {
  20594. if (this._fogMode === value) {
  20595. return;
  20596. }
  20597. this._fogMode = value;
  20598. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20604. get: function () {
  20605. return this._shadowsEnabled;
  20606. },
  20607. set: function (value) {
  20608. if (this._shadowsEnabled === value) {
  20609. return;
  20610. }
  20611. this._shadowsEnabled = value;
  20612. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20613. },
  20614. enumerable: true,
  20615. configurable: true
  20616. });
  20617. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20618. get: function () {
  20619. return this._lightsEnabled;
  20620. },
  20621. set: function (value) {
  20622. if (this._lightsEnabled === value) {
  20623. return;
  20624. }
  20625. this._lightsEnabled = value;
  20626. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20627. },
  20628. enumerable: true,
  20629. configurable: true
  20630. });
  20631. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20632. /** The default material used on meshes when no material is affected */
  20633. get: function () {
  20634. if (!this._defaultMaterial) {
  20635. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20636. }
  20637. return this._defaultMaterial;
  20638. },
  20639. /** The default material used on meshes when no material is affected */
  20640. set: function (value) {
  20641. this._defaultMaterial = value;
  20642. },
  20643. enumerable: true,
  20644. configurable: true
  20645. });
  20646. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20647. get: function () {
  20648. return this._texturesEnabled;
  20649. },
  20650. set: function (value) {
  20651. if (this._texturesEnabled === value) {
  20652. return;
  20653. }
  20654. this._texturesEnabled = value;
  20655. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20656. },
  20657. enumerable: true,
  20658. configurable: true
  20659. });
  20660. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20661. get: function () {
  20662. return this._skeletonsEnabled;
  20663. },
  20664. set: function (value) {
  20665. if (this._skeletonsEnabled === value) {
  20666. return;
  20667. }
  20668. this._skeletonsEnabled = value;
  20669. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20675. get: function () {
  20676. if (!this._postProcessRenderPipelineManager) {
  20677. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20678. }
  20679. return this._postProcessRenderPipelineManager;
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20685. get: function () {
  20686. if (!this._mainSoundTrack) {
  20687. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20688. }
  20689. return this._mainSoundTrack;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20695. get: function () {
  20696. return this._alternateRendering;
  20697. },
  20698. enumerable: true,
  20699. configurable: true
  20700. });
  20701. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20702. get: function () {
  20703. return this._frustumPlanes;
  20704. },
  20705. enumerable: true,
  20706. configurable: true
  20707. });
  20708. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20709. /**
  20710. * Gets the current geometry buffer associated to the scene.
  20711. */
  20712. get: function () {
  20713. return this._geometryBufferRenderer;
  20714. },
  20715. /**
  20716. * Sets the current geometry buffer for the scene.
  20717. */
  20718. set: function (geometryBufferRenderer) {
  20719. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20720. this._geometryBufferRenderer = geometryBufferRenderer;
  20721. }
  20722. },
  20723. enumerable: true,
  20724. configurable: true
  20725. });
  20726. Object.defineProperty(Scene.prototype, "debugLayer", {
  20727. // Properties
  20728. get: function () {
  20729. if (!this._debugLayer) {
  20730. this._debugLayer = new BABYLON.DebugLayer(this);
  20731. }
  20732. return this._debugLayer;
  20733. },
  20734. enumerable: true,
  20735. configurable: true
  20736. });
  20737. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20738. get: function () {
  20739. return this._workerCollisions;
  20740. },
  20741. set: function (enabled) {
  20742. if (!BABYLON.CollisionCoordinatorLegacy) {
  20743. return;
  20744. }
  20745. enabled = (enabled && !!Worker);
  20746. this._workerCollisions = enabled;
  20747. if (this.collisionCoordinator) {
  20748. this.collisionCoordinator.destroy();
  20749. }
  20750. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20751. this.collisionCoordinator.init(this);
  20752. },
  20753. enumerable: true,
  20754. configurable: true
  20755. });
  20756. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20757. get: function () {
  20758. return this._selectionOctree;
  20759. },
  20760. enumerable: true,
  20761. configurable: true
  20762. });
  20763. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20764. /**
  20765. * The mesh that is currently under the pointer.
  20766. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20767. */
  20768. get: function () {
  20769. return this._pointerOverMesh;
  20770. },
  20771. enumerable: true,
  20772. configurable: true
  20773. });
  20774. Object.defineProperty(Scene.prototype, "pointerX", {
  20775. /**
  20776. * Current on-screen X position of the pointer
  20777. * @return {number} X position of the pointer
  20778. */
  20779. get: function () {
  20780. return this._pointerX;
  20781. },
  20782. enumerable: true,
  20783. configurable: true
  20784. });
  20785. Object.defineProperty(Scene.prototype, "pointerY", {
  20786. /**
  20787. * Current on-screen Y position of the pointer
  20788. * @return {number} Y position of the pointer
  20789. */
  20790. get: function () {
  20791. return this._pointerY;
  20792. },
  20793. enumerable: true,
  20794. configurable: true
  20795. });
  20796. Scene.prototype.getCachedMaterial = function () {
  20797. return this._cachedMaterial;
  20798. };
  20799. Scene.prototype.getCachedEffect = function () {
  20800. return this._cachedEffect;
  20801. };
  20802. Scene.prototype.getCachedVisibility = function () {
  20803. return this._cachedVisibility;
  20804. };
  20805. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20806. if (visibility === void 0) { visibility = 1; }
  20807. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20808. };
  20809. Scene.prototype.getBoundingBoxRenderer = function () {
  20810. if (!this._boundingBoxRenderer) {
  20811. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20812. }
  20813. return this._boundingBoxRenderer;
  20814. };
  20815. Scene.prototype.getOutlineRenderer = function () {
  20816. return this._outlineRenderer;
  20817. };
  20818. Scene.prototype.getEngine = function () {
  20819. return this._engine;
  20820. };
  20821. Scene.prototype.getTotalVertices = function () {
  20822. return this._totalVertices.current;
  20823. };
  20824. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20825. get: function () {
  20826. return this._totalVertices;
  20827. },
  20828. enumerable: true,
  20829. configurable: true
  20830. });
  20831. Scene.prototype.getActiveIndices = function () {
  20832. return this._activeIndices.current;
  20833. };
  20834. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20835. get: function () {
  20836. return this._activeIndices;
  20837. },
  20838. enumerable: true,
  20839. configurable: true
  20840. });
  20841. Scene.prototype.getActiveParticles = function () {
  20842. return this._activeParticles.current;
  20843. };
  20844. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20845. get: function () {
  20846. return this._activeParticles;
  20847. },
  20848. enumerable: true,
  20849. configurable: true
  20850. });
  20851. Scene.prototype.getActiveBones = function () {
  20852. return this._activeBones.current;
  20853. };
  20854. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20855. get: function () {
  20856. return this._activeBones;
  20857. },
  20858. enumerable: true,
  20859. configurable: true
  20860. });
  20861. // Stats
  20862. Scene.prototype.getInterFramePerfCounter = function () {
  20863. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20864. return 0;
  20865. };
  20866. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20867. get: function () {
  20868. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20869. return null;
  20870. },
  20871. enumerable: true,
  20872. configurable: true
  20873. });
  20874. Scene.prototype.getLastFrameDuration = function () {
  20875. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20876. return 0;
  20877. };
  20878. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20879. get: function () {
  20880. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20881. return null;
  20882. },
  20883. enumerable: true,
  20884. configurable: true
  20885. });
  20886. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20887. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20888. return 0;
  20889. };
  20890. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20891. get: function () {
  20892. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20893. return null;
  20894. },
  20895. enumerable: true,
  20896. configurable: true
  20897. });
  20898. Scene.prototype.getActiveMeshes = function () {
  20899. return this._activeMeshes;
  20900. };
  20901. Scene.prototype.getRenderTargetsDuration = function () {
  20902. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20903. return 0;
  20904. };
  20905. Scene.prototype.getRenderDuration = function () {
  20906. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20907. return 0;
  20908. };
  20909. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20910. get: function () {
  20911. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20912. return null;
  20913. },
  20914. enumerable: true,
  20915. configurable: true
  20916. });
  20917. Scene.prototype.getParticlesDuration = function () {
  20918. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20919. return 0;
  20920. };
  20921. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20922. get: function () {
  20923. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20924. return null;
  20925. },
  20926. enumerable: true,
  20927. configurable: true
  20928. });
  20929. Scene.prototype.getSpritesDuration = function () {
  20930. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20931. return 0;
  20932. };
  20933. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20934. get: function () {
  20935. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20936. return null;
  20937. },
  20938. enumerable: true,
  20939. configurable: true
  20940. });
  20941. Scene.prototype.getAnimationRatio = function () {
  20942. return this._animationRatio;
  20943. };
  20944. Scene.prototype.getRenderId = function () {
  20945. return this._renderId;
  20946. };
  20947. Scene.prototype.incrementRenderId = function () {
  20948. this._renderId++;
  20949. };
  20950. Scene.prototype._updatePointerPosition = function (evt) {
  20951. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20952. if (!canvasRect) {
  20953. return;
  20954. }
  20955. this._pointerX = evt.clientX - canvasRect.left;
  20956. this._pointerY = evt.clientY - canvasRect.top;
  20957. this._unTranslatedPointerX = this._pointerX;
  20958. this._unTranslatedPointerY = this._pointerY;
  20959. };
  20960. Scene.prototype._createUbo = function () {
  20961. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20962. this._sceneUbo.addUniform("viewProjection", 16);
  20963. this._sceneUbo.addUniform("view", 16);
  20964. };
  20965. Scene.prototype._createAlternateUbo = function () {
  20966. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20967. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20968. this._alternateSceneUbo.addUniform("view", 16);
  20969. };
  20970. // Pointers handling
  20971. /**
  20972. * Use this method to simulate a pointer move on a mesh
  20973. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20974. */
  20975. Scene.prototype.simulatePointerMove = function (pickResult) {
  20976. var evt = new PointerEvent("pointermove");
  20977. return this._processPointerMove(pickResult, evt);
  20978. };
  20979. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20980. var canvas = this._engine.getRenderingCanvas();
  20981. if (!canvas) {
  20982. return this;
  20983. }
  20984. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20985. this.setPointerOverSprite(null);
  20986. this.setPointerOverMesh(pickResult.pickedMesh);
  20987. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20988. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20989. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20990. }
  20991. else {
  20992. canvas.style.cursor = this.hoverCursor;
  20993. }
  20994. }
  20995. else {
  20996. canvas.style.cursor = this.defaultCursor;
  20997. }
  20998. }
  20999. else {
  21000. this.setPointerOverMesh(null);
  21001. // Sprites
  21002. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21003. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21004. this.setPointerOverSprite(pickResult.pickedSprite);
  21005. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21006. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21007. }
  21008. else {
  21009. canvas.style.cursor = this.hoverCursor;
  21010. }
  21011. }
  21012. else {
  21013. this.setPointerOverSprite(null);
  21014. // Restore pointer
  21015. canvas.style.cursor = this.defaultCursor;
  21016. }
  21017. }
  21018. if (pickResult) {
  21019. if (this.onPointerMove) {
  21020. this.onPointerMove(evt, pickResult);
  21021. }
  21022. if (this.onPointerObservable.hasObservers()) {
  21023. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21024. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21025. this.onPointerObservable.notifyObservers(pi, type);
  21026. }
  21027. }
  21028. return this;
  21029. };
  21030. /**
  21031. * Use this method to simulate a pointer down on a mesh
  21032. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21033. */
  21034. Scene.prototype.simulatePointerDown = function (pickResult) {
  21035. var evt = new PointerEvent("pointerdown");
  21036. return this._processPointerDown(pickResult, evt);
  21037. };
  21038. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21039. var _this = this;
  21040. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21041. this._pickedDownMesh = pickResult.pickedMesh;
  21042. var actionManager = pickResult.pickedMesh.actionManager;
  21043. if (actionManager) {
  21044. if (actionManager.hasPickTriggers) {
  21045. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21046. switch (evt.button) {
  21047. case 0:
  21048. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21049. break;
  21050. case 1:
  21051. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21052. break;
  21053. case 2:
  21054. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21055. break;
  21056. }
  21057. }
  21058. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21059. window.setTimeout(function () {
  21060. 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);
  21061. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21062. if (_this._totalPointersPressed !== 0 &&
  21063. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21064. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21065. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21066. _this._startingPointerTime = 0;
  21067. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21068. }
  21069. }
  21070. }, Scene.LongPressDelay);
  21071. }
  21072. }
  21073. }
  21074. if (pickResult) {
  21075. if (this.onPointerDown) {
  21076. this.onPointerDown(evt, pickResult);
  21077. }
  21078. if (this.onPointerObservable.hasObservers()) {
  21079. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21080. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21081. this.onPointerObservable.notifyObservers(pi, type);
  21082. }
  21083. }
  21084. return this;
  21085. };
  21086. /**
  21087. * Use this method to simulate a pointer up on a mesh
  21088. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21089. */
  21090. Scene.prototype.simulatePointerUp = function (pickResult) {
  21091. var evt = new PointerEvent("pointerup");
  21092. var clickInfo = new ClickInfo();
  21093. clickInfo.singleClick = true;
  21094. clickInfo.ignore = true;
  21095. return this._processPointerUp(pickResult, evt, clickInfo);
  21096. };
  21097. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21098. if (pickResult && pickResult && pickResult.pickedMesh) {
  21099. this._pickedUpMesh = pickResult.pickedMesh;
  21100. if (this._pickedDownMesh === this._pickedUpMesh) {
  21101. if (this.onPointerPick) {
  21102. this.onPointerPick(evt, pickResult);
  21103. }
  21104. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21105. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21106. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21107. this.onPointerObservable.notifyObservers(pi, type);
  21108. }
  21109. }
  21110. if (pickResult.pickedMesh.actionManager) {
  21111. if (clickInfo.ignore) {
  21112. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21113. }
  21114. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21115. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21116. }
  21117. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21118. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21119. }
  21120. }
  21121. }
  21122. if (this._pickedDownMesh &&
  21123. this._pickedDownMesh.actionManager &&
  21124. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21125. this._pickedDownMesh !== this._pickedUpMesh) {
  21126. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21127. }
  21128. if (this.onPointerUp) {
  21129. this.onPointerUp(evt, pickResult);
  21130. }
  21131. if (this.onPointerObservable.hasObservers()) {
  21132. if (!clickInfo.ignore) {
  21133. if (!clickInfo.hasSwiped) {
  21134. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21135. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21136. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21137. this.onPointerObservable.notifyObservers(pi, type);
  21138. }
  21139. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21140. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21141. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21142. this.onPointerObservable.notifyObservers(pi, type);
  21143. }
  21144. }
  21145. }
  21146. else {
  21147. var type = BABYLON.PointerEventTypes.POINTERUP;
  21148. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21149. this.onPointerObservable.notifyObservers(pi, type);
  21150. }
  21151. }
  21152. return this;
  21153. };
  21154. /**
  21155. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21156. * @param attachUp defines if you want to attach events to pointerup
  21157. * @param attachDown defines if you want to attach events to pointerdown
  21158. * @param attachMove defines if you want to attach events to pointermove
  21159. */
  21160. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21161. var _this = this;
  21162. if (attachUp === void 0) { attachUp = true; }
  21163. if (attachDown === void 0) { attachDown = true; }
  21164. if (attachMove === void 0) { attachMove = true; }
  21165. this._initActionManager = function (act, clickInfo) {
  21166. if (!_this._meshPickProceed) {
  21167. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21168. _this._currentPickResult = pickResult;
  21169. if (pickResult) {
  21170. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21171. }
  21172. _this._meshPickProceed = true;
  21173. }
  21174. return act;
  21175. };
  21176. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21177. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21178. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21179. btn !== _this._previousButtonPressed) {
  21180. _this._doubleClickOccured = false;
  21181. clickInfo.singleClick = true;
  21182. clickInfo.ignore = false;
  21183. cb(clickInfo, _this._currentPickResult);
  21184. }
  21185. };
  21186. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21187. var clickInfo = new ClickInfo();
  21188. _this._currentPickResult = null;
  21189. var act = null;
  21190. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21191. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21192. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21193. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21194. act = _this._initActionManager(act, clickInfo);
  21195. if (act)
  21196. checkPicking = act.hasPickTriggers;
  21197. }
  21198. if (checkPicking) {
  21199. var btn = evt.button;
  21200. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21201. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21202. if (!clickInfo.hasSwiped) {
  21203. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21204. if (!checkSingleClickImmediately) {
  21205. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21206. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21207. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21208. act = _this._initActionManager(act, clickInfo);
  21209. if (act)
  21210. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21211. }
  21212. }
  21213. if (checkSingleClickImmediately) {
  21214. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21215. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21216. btn !== _this._previousButtonPressed) {
  21217. clickInfo.singleClick = true;
  21218. cb(clickInfo, _this._currentPickResult);
  21219. }
  21220. }
  21221. else {
  21222. // wait that no double click has been raised during the double click delay
  21223. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21224. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21225. }
  21226. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21227. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21228. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21229. act = _this._initActionManager(act, clickInfo);
  21230. if (act)
  21231. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21232. }
  21233. if (checkDoubleClick) {
  21234. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21235. if (btn === _this._previousButtonPressed &&
  21236. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21237. !_this._doubleClickOccured) {
  21238. // pointer has not moved for 2 clicks, it's a double click
  21239. if (!clickInfo.hasSwiped &&
  21240. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21241. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21242. _this._previousStartingPointerTime = 0;
  21243. _this._doubleClickOccured = true;
  21244. clickInfo.doubleClick = true;
  21245. clickInfo.ignore = false;
  21246. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21247. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21248. }
  21249. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21250. cb(clickInfo, _this._currentPickResult);
  21251. }
  21252. else {
  21253. _this._doubleClickOccured = false;
  21254. _this._previousStartingPointerTime = _this._startingPointerTime;
  21255. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21256. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21257. _this._previousButtonPressed = btn;
  21258. if (Scene.ExclusiveDoubleClickMode) {
  21259. if (_this._previousDelayedSimpleClickTimeout) {
  21260. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21261. }
  21262. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21263. cb(clickInfo, _this._previousPickResult);
  21264. }
  21265. else {
  21266. cb(clickInfo, _this._currentPickResult);
  21267. }
  21268. }
  21269. }
  21270. else {
  21271. _this._doubleClickOccured = false;
  21272. _this._previousStartingPointerTime = _this._startingPointerTime;
  21273. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21274. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21275. _this._previousButtonPressed = btn;
  21276. }
  21277. }
  21278. }
  21279. }
  21280. clickInfo.ignore = true;
  21281. cb(clickInfo, _this._currentPickResult);
  21282. };
  21283. this._spritePredicate = function (sprite) {
  21284. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21285. };
  21286. this._onPointerMove = function (evt) {
  21287. _this._updatePointerPosition(evt);
  21288. // PreObservable support
  21289. if (_this.onPrePointerObservable.hasObservers()) {
  21290. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21291. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21292. _this.onPrePointerObservable.notifyObservers(pi, type);
  21293. if (pi.skipOnPointerObservable) {
  21294. return;
  21295. }
  21296. }
  21297. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21298. return;
  21299. }
  21300. if (!_this.pointerMovePredicate) {
  21301. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21302. }
  21303. // Meshes
  21304. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21305. _this._processPointerMove(pickResult, evt);
  21306. };
  21307. this._onPointerDown = function (evt) {
  21308. _this._totalPointersPressed++;
  21309. _this._pickedDownMesh = null;
  21310. _this._meshPickProceed = false;
  21311. _this._updatePointerPosition(evt);
  21312. if (_this.preventDefaultOnPointerDown && canvas) {
  21313. evt.preventDefault();
  21314. canvas.focus();
  21315. }
  21316. // PreObservable support
  21317. if (_this.onPrePointerObservable.hasObservers()) {
  21318. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21319. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21320. _this.onPrePointerObservable.notifyObservers(pi, type);
  21321. if (pi.skipOnPointerObservable) {
  21322. return;
  21323. }
  21324. }
  21325. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21326. return;
  21327. }
  21328. _this._startingPointerPosition.x = _this._pointerX;
  21329. _this._startingPointerPosition.y = _this._pointerY;
  21330. _this._startingPointerTime = new Date().getTime();
  21331. if (!_this.pointerDownPredicate) {
  21332. _this.pointerDownPredicate = function (mesh) {
  21333. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21334. };
  21335. }
  21336. // Meshes
  21337. _this._pickedDownMesh = null;
  21338. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21339. _this._processPointerDown(pickResult, evt);
  21340. // Sprites
  21341. _this._pickedDownSprite = null;
  21342. if (_this.spriteManagers.length > 0) {
  21343. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21344. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21345. if (pickResult.pickedSprite.actionManager) {
  21346. _this._pickedDownSprite = pickResult.pickedSprite;
  21347. switch (evt.button) {
  21348. case 0:
  21349. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21350. break;
  21351. case 1:
  21352. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21353. break;
  21354. case 2:
  21355. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21356. break;
  21357. }
  21358. if (pickResult.pickedSprite.actionManager) {
  21359. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21360. }
  21361. }
  21362. }
  21363. }
  21364. };
  21365. this._onPointerUp = function (evt) {
  21366. if (_this._totalPointersPressed === 0) {
  21367. return; // So we need to test it the pointer down was pressed before.
  21368. }
  21369. _this._totalPointersPressed--;
  21370. _this._pickedUpMesh = null;
  21371. _this._meshPickProceed = false;
  21372. _this._updatePointerPosition(evt);
  21373. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21374. // PreObservable support
  21375. if (_this.onPrePointerObservable.hasObservers()) {
  21376. if (!clickInfo.ignore) {
  21377. if (!clickInfo.hasSwiped) {
  21378. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21379. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21380. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21381. _this.onPrePointerObservable.notifyObservers(pi, type);
  21382. if (pi.skipOnPointerObservable) {
  21383. return;
  21384. }
  21385. }
  21386. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21387. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21388. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21389. _this.onPrePointerObservable.notifyObservers(pi, type);
  21390. if (pi.skipOnPointerObservable) {
  21391. return;
  21392. }
  21393. }
  21394. }
  21395. }
  21396. else {
  21397. var type = BABYLON.PointerEventTypes.POINTERUP;
  21398. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21399. _this.onPrePointerObservable.notifyObservers(pi, type);
  21400. if (pi.skipOnPointerObservable) {
  21401. return;
  21402. }
  21403. }
  21404. }
  21405. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21406. return;
  21407. }
  21408. if (!_this.pointerUpPredicate) {
  21409. _this.pointerUpPredicate = function (mesh) {
  21410. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21411. };
  21412. }
  21413. // Meshes
  21414. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21415. _this._initActionManager(null, clickInfo);
  21416. }
  21417. if (!pickResult) {
  21418. pickResult = _this._currentPickResult;
  21419. }
  21420. _this._processPointerUp(pickResult, evt, clickInfo);
  21421. // Sprites
  21422. if (_this.spriteManagers.length > 0) {
  21423. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21424. if (spritePickResult) {
  21425. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21426. if (spritePickResult.pickedSprite.actionManager) {
  21427. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21428. if (spritePickResult.pickedSprite.actionManager) {
  21429. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21430. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21431. }
  21432. }
  21433. }
  21434. }
  21435. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21436. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21437. }
  21438. }
  21439. }
  21440. _this._previousPickResult = _this._currentPickResult;
  21441. });
  21442. };
  21443. this._onKeyDown = function (evt) {
  21444. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21445. if (_this.onPreKeyboardObservable.hasObservers()) {
  21446. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21447. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21448. if (pi.skipOnPointerObservable) {
  21449. return;
  21450. }
  21451. }
  21452. if (_this.onKeyboardObservable.hasObservers()) {
  21453. var pi = new BABYLON.KeyboardInfo(type, evt);
  21454. _this.onKeyboardObservable.notifyObservers(pi, type);
  21455. }
  21456. if (_this.actionManager) {
  21457. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21458. }
  21459. };
  21460. this._onKeyUp = function (evt) {
  21461. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21462. if (_this.onPreKeyboardObservable.hasObservers()) {
  21463. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21464. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21465. if (pi.skipOnPointerObservable) {
  21466. return;
  21467. }
  21468. }
  21469. if (_this.onKeyboardObservable.hasObservers()) {
  21470. var pi = new BABYLON.KeyboardInfo(type, evt);
  21471. _this.onKeyboardObservable.notifyObservers(pi, type);
  21472. }
  21473. if (_this.actionManager) {
  21474. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21475. }
  21476. };
  21477. var engine = this.getEngine();
  21478. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21479. if (!canvas) {
  21480. return;
  21481. }
  21482. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21483. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21484. });
  21485. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21486. if (!canvas) {
  21487. return;
  21488. }
  21489. canvas.removeEventListener("keydown", _this._onKeyDown);
  21490. canvas.removeEventListener("keyup", _this._onKeyUp);
  21491. });
  21492. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21493. var canvas = this._engine.getRenderingCanvas();
  21494. if (!canvas) {
  21495. return;
  21496. }
  21497. if (attachMove) {
  21498. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21499. // Wheel
  21500. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21501. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21502. }
  21503. if (attachDown) {
  21504. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21505. }
  21506. if (attachUp) {
  21507. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21508. }
  21509. canvas.tabIndex = 1;
  21510. };
  21511. Scene.prototype.detachControl = function () {
  21512. var engine = this.getEngine();
  21513. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21514. var canvas = engine.getRenderingCanvas();
  21515. if (!canvas) {
  21516. return;
  21517. }
  21518. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21519. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21520. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21521. if (this._onCanvasBlurObserver) {
  21522. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21523. }
  21524. if (this._onCanvasFocusObserver) {
  21525. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21526. }
  21527. // Wheel
  21528. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21529. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21530. // Keyboard
  21531. canvas.removeEventListener("keydown", this._onKeyDown);
  21532. canvas.removeEventListener("keyup", this._onKeyUp);
  21533. // Observables
  21534. this.onKeyboardObservable.clear();
  21535. this.onPreKeyboardObservable.clear();
  21536. this.onPointerObservable.clear();
  21537. this.onPrePointerObservable.clear();
  21538. };
  21539. /**
  21540. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21541. * Delay loaded resources are not taking in account
  21542. * @return true if all required resources are ready
  21543. */
  21544. Scene.prototype.isReady = function () {
  21545. if (this._isDisposed) {
  21546. return false;
  21547. }
  21548. if (this._pendingData.length > 0) {
  21549. return false;
  21550. }
  21551. var index;
  21552. var engine = this.getEngine();
  21553. // Geometries
  21554. for (index = 0; index < this._geometries.length; index++) {
  21555. var geometry = this._geometries[index];
  21556. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21557. return false;
  21558. }
  21559. }
  21560. // Meshes
  21561. for (index = 0; index < this.meshes.length; index++) {
  21562. var mesh = this.meshes[index];
  21563. if (!mesh.isEnabled()) {
  21564. continue;
  21565. }
  21566. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21567. continue;
  21568. }
  21569. if (!mesh.isReady()) {
  21570. return false;
  21571. }
  21572. // Highlight layers
  21573. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21574. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21575. var layer = _a[_i];
  21576. if (!layer.hasMesh(mesh)) {
  21577. continue;
  21578. }
  21579. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21580. var subMesh = _c[_b];
  21581. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21582. return false;
  21583. }
  21584. }
  21585. }
  21586. }
  21587. return true;
  21588. };
  21589. Scene.prototype.resetCachedMaterial = function () {
  21590. this._cachedMaterial = null;
  21591. this._cachedEffect = null;
  21592. this._cachedVisibility = null;
  21593. };
  21594. Scene.prototype.registerBeforeRender = function (func) {
  21595. this.onBeforeRenderObservable.add(func);
  21596. };
  21597. Scene.prototype.unregisterBeforeRender = function (func) {
  21598. this.onBeforeRenderObservable.removeCallback(func);
  21599. };
  21600. Scene.prototype.registerAfterRender = function (func) {
  21601. this.onAfterRenderObservable.add(func);
  21602. };
  21603. Scene.prototype.unregisterAfterRender = function (func) {
  21604. this.onAfterRenderObservable.removeCallback(func);
  21605. };
  21606. Scene.prototype._executeOnceBeforeRender = function (func) {
  21607. var _this = this;
  21608. var execFunc = function () {
  21609. func();
  21610. setTimeout(function () {
  21611. _this.unregisterBeforeRender(execFunc);
  21612. });
  21613. };
  21614. this.registerBeforeRender(execFunc);
  21615. };
  21616. /**
  21617. * The provided function will run before render once and will be disposed afterwards.
  21618. * A timeout delay can be provided so that the function will be executed in N ms.
  21619. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21620. * @param func The function to be executed.
  21621. * @param timeout optional delay in ms
  21622. */
  21623. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21624. var _this = this;
  21625. if (timeout !== undefined) {
  21626. setTimeout(function () {
  21627. _this._executeOnceBeforeRender(func);
  21628. }, timeout);
  21629. }
  21630. else {
  21631. this._executeOnceBeforeRender(func);
  21632. }
  21633. };
  21634. Scene.prototype._addPendingData = function (data) {
  21635. this._pendingData.push(data);
  21636. };
  21637. Scene.prototype._removePendingData = function (data) {
  21638. var wasLoading = this.isLoading;
  21639. var index = this._pendingData.indexOf(data);
  21640. if (index !== -1) {
  21641. this._pendingData.splice(index, 1);
  21642. }
  21643. if (wasLoading && !this.isLoading) {
  21644. this.onDataLoadedObservable.notifyObservers(this);
  21645. }
  21646. };
  21647. Scene.prototype.getWaitingItemsCount = function () {
  21648. return this._pendingData.length;
  21649. };
  21650. Object.defineProperty(Scene.prototype, "isLoading", {
  21651. get: function () {
  21652. return this._pendingData.length > 0;
  21653. },
  21654. enumerable: true,
  21655. configurable: true
  21656. });
  21657. /**
  21658. * Registers a function to be executed when the scene is ready.
  21659. * @param {Function} func - the function to be executed.
  21660. */
  21661. Scene.prototype.executeWhenReady = function (func) {
  21662. var _this = this;
  21663. this.onReadyObservable.add(func);
  21664. if (this._executeWhenReadyTimeoutId !== -1) {
  21665. return;
  21666. }
  21667. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21668. _this._checkIsReady();
  21669. }, 150);
  21670. };
  21671. Scene.prototype._checkIsReady = function () {
  21672. var _this = this;
  21673. if (this.isReady()) {
  21674. this.onReadyObservable.notifyObservers(this);
  21675. this.onReadyObservable.clear();
  21676. this._executeWhenReadyTimeoutId = -1;
  21677. return;
  21678. }
  21679. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21680. _this._checkIsReady();
  21681. }, 150);
  21682. };
  21683. // Animations
  21684. /**
  21685. * Will start the animation sequence of a given target
  21686. * @param target - the target
  21687. * @param {number} from - from which frame should animation start
  21688. * @param {number} to - till which frame should animation run.
  21689. * @param {boolean} [loop] - should the animation loop
  21690. * @param {number} [speedRatio] - the speed in which to run the animation
  21691. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21692. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21693. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21694. * See BABYLON.Animatable
  21695. */
  21696. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21697. if (speedRatio === void 0) { speedRatio = 1.0; }
  21698. if (from > to && speedRatio > 0) {
  21699. speedRatio *= -1;
  21700. }
  21701. this.stopAnimation(target);
  21702. if (!animatable) {
  21703. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21704. }
  21705. // Local animations
  21706. if (target.animations) {
  21707. animatable.appendAnimations(target, target.animations);
  21708. }
  21709. // Children animations
  21710. if (target.getAnimatables) {
  21711. var animatables = target.getAnimatables();
  21712. for (var index = 0; index < animatables.length; index++) {
  21713. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21714. }
  21715. }
  21716. animatable.reset();
  21717. return animatable;
  21718. };
  21719. /**
  21720. * Begin a new animation on a given node
  21721. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21722. * @param {BABYLON.Animation[]} defines the list of animations to start
  21723. * @param {number} from defines the initial value
  21724. * @param {number} to defines the final value
  21725. * @param {boolean} loop defines if you want animation to loop (off by default)
  21726. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21727. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21728. * @returns the list of created animatables
  21729. */
  21730. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21731. if (speedRatio === undefined) {
  21732. speedRatio = 1.0;
  21733. }
  21734. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21735. return animatable;
  21736. };
  21737. /**
  21738. * Begin a new animation on a given node and its hierarchy
  21739. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21740. * @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.
  21741. * @param {BABYLON.Animation[]} defines the list of animations to start
  21742. * @param {number} from defines the initial value
  21743. * @param {number} to defines the final value
  21744. * @param {boolean} loop defines if you want animation to loop (off by default)
  21745. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21746. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21747. * @returns the list of animatables created for all nodes
  21748. */
  21749. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21750. var children = target.getDescendants(directDescendantsOnly);
  21751. var result = [];
  21752. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21753. var child = children_1[_i];
  21754. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21755. }
  21756. return result;
  21757. };
  21758. Scene.prototype.getAnimatableByTarget = function (target) {
  21759. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21760. if (this._activeAnimatables[index].target === target) {
  21761. return this._activeAnimatables[index];
  21762. }
  21763. }
  21764. return null;
  21765. };
  21766. Object.defineProperty(Scene.prototype, "animatables", {
  21767. get: function () {
  21768. return this._activeAnimatables;
  21769. },
  21770. enumerable: true,
  21771. configurable: true
  21772. });
  21773. /**
  21774. * Will stop the animation of the given target
  21775. * @param target - the target
  21776. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21777. * @see beginAnimation
  21778. */
  21779. Scene.prototype.stopAnimation = function (target, animationName) {
  21780. var animatable = this.getAnimatableByTarget(target);
  21781. if (animatable) {
  21782. animatable.stop(animationName);
  21783. }
  21784. };
  21785. /**
  21786. * Stops and removes all animations that have been applied to the scene
  21787. */
  21788. Scene.prototype.stopAllAnimations = function () {
  21789. if (this._activeAnimatables) {
  21790. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21791. this._activeAnimatables[i].stop();
  21792. }
  21793. this._activeAnimatables = [];
  21794. }
  21795. };
  21796. Scene.prototype._animate = function () {
  21797. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21798. return;
  21799. }
  21800. // Getting time
  21801. var now = BABYLON.Tools.Now;
  21802. if (!this._animationTimeLast) {
  21803. if (this._pendingData.length > 0) {
  21804. return;
  21805. }
  21806. this._animationTimeLast = now;
  21807. }
  21808. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21809. this._animationTime += deltaTime;
  21810. this._animationTimeLast = now;
  21811. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21812. this._activeAnimatables[index]._animate(this._animationTime);
  21813. }
  21814. };
  21815. // Matrix
  21816. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21817. this._useAlternateCameraConfiguration = active;
  21818. };
  21819. Scene.prototype.getViewMatrix = function () {
  21820. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21821. };
  21822. Scene.prototype.getProjectionMatrix = function () {
  21823. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21824. };
  21825. Scene.prototype.getTransformMatrix = function () {
  21826. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21827. };
  21828. Scene.prototype.setTransformMatrix = function (view, projection) {
  21829. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21830. return;
  21831. }
  21832. this._viewUpdateFlag = view.updateFlag;
  21833. this._projectionUpdateFlag = projection.updateFlag;
  21834. this._viewMatrix = view;
  21835. this._projectionMatrix = projection;
  21836. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21837. // Update frustum
  21838. if (!this._frustumPlanes) {
  21839. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21840. }
  21841. else {
  21842. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21843. }
  21844. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21845. var otherCamera = this.activeCamera._alternateCamera;
  21846. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21847. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21848. }
  21849. if (this._sceneUbo.useUbo) {
  21850. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21851. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21852. this._sceneUbo.update();
  21853. }
  21854. };
  21855. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21856. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21857. return;
  21858. }
  21859. this._alternateViewUpdateFlag = view.updateFlag;
  21860. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21861. this._alternateViewMatrix = view;
  21862. this._alternateProjectionMatrix = projection;
  21863. if (!this._alternateTransformMatrix) {
  21864. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21865. }
  21866. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21867. if (!this._alternateSceneUbo) {
  21868. this._createAlternateUbo();
  21869. }
  21870. if (this._alternateSceneUbo.useUbo) {
  21871. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21872. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21873. this._alternateSceneUbo.update();
  21874. }
  21875. };
  21876. Scene.prototype.getSceneUniformBuffer = function () {
  21877. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21878. };
  21879. // Methods
  21880. Scene.prototype.getUniqueId = function () {
  21881. var result = Scene._uniqueIdCounter;
  21882. Scene._uniqueIdCounter++;
  21883. return result;
  21884. };
  21885. Scene.prototype.addMesh = function (newMesh) {
  21886. this.meshes.push(newMesh);
  21887. //notify the collision coordinator
  21888. if (this.collisionCoordinator) {
  21889. this.collisionCoordinator.onMeshAdded(newMesh);
  21890. }
  21891. newMesh._resyncLightSources();
  21892. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21893. };
  21894. Scene.prototype.removeMesh = function (toRemove) {
  21895. var index = this.meshes.indexOf(toRemove);
  21896. if (index !== -1) {
  21897. // Remove from the scene if mesh found
  21898. this.meshes.splice(index, 1);
  21899. }
  21900. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21901. return index;
  21902. };
  21903. Scene.prototype.addTransformNode = function (newTransformNode) {
  21904. this.transformNodes.push(newTransformNode);
  21905. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21906. };
  21907. Scene.prototype.removeTransformNode = function (toRemove) {
  21908. var index = this.transformNodes.indexOf(toRemove);
  21909. if (index !== -1) {
  21910. // Remove from the scene if found
  21911. this.transformNodes.splice(index, 1);
  21912. }
  21913. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21914. return index;
  21915. };
  21916. Scene.prototype.removeSkeleton = function (toRemove) {
  21917. var index = this.skeletons.indexOf(toRemove);
  21918. if (index !== -1) {
  21919. // Remove from the scene if found
  21920. this.skeletons.splice(index, 1);
  21921. }
  21922. return index;
  21923. };
  21924. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21925. var index = this.morphTargetManagers.indexOf(toRemove);
  21926. if (index !== -1) {
  21927. // Remove from the scene if found
  21928. this.morphTargetManagers.splice(index, 1);
  21929. }
  21930. return index;
  21931. };
  21932. Scene.prototype.removeLight = function (toRemove) {
  21933. var index = this.lights.indexOf(toRemove);
  21934. if (index !== -1) {
  21935. // Remove from meshes
  21936. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21937. var mesh = _a[_i];
  21938. mesh._removeLightSource(toRemove);
  21939. }
  21940. // Remove from the scene if mesh found
  21941. this.lights.splice(index, 1);
  21942. this.sortLightsByPriority();
  21943. }
  21944. this.onLightRemovedObservable.notifyObservers(toRemove);
  21945. return index;
  21946. };
  21947. Scene.prototype.removeCamera = function (toRemove) {
  21948. var index = this.cameras.indexOf(toRemove);
  21949. if (index !== -1) {
  21950. // Remove from the scene if mesh found
  21951. this.cameras.splice(index, 1);
  21952. }
  21953. // Remove from activeCameras
  21954. var index2 = this.activeCameras.indexOf(toRemove);
  21955. if (index2 !== -1) {
  21956. // Remove from the scene if mesh found
  21957. this.activeCameras.splice(index2, 1);
  21958. }
  21959. // Reset the activeCamera
  21960. if (this.activeCamera === toRemove) {
  21961. if (this.cameras.length > 0) {
  21962. this.activeCamera = this.cameras[0];
  21963. }
  21964. else {
  21965. this.activeCamera = null;
  21966. }
  21967. }
  21968. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21969. return index;
  21970. };
  21971. Scene.prototype.removeParticleSystem = function (toRemove) {
  21972. var index = this.particleSystems.indexOf(toRemove);
  21973. if (index !== -1) {
  21974. this.particleSystems.splice(index, 1);
  21975. }
  21976. return index;
  21977. };
  21978. ;
  21979. Scene.prototype.removeAnimation = function (toRemove) {
  21980. var index = this.animations.indexOf(toRemove);
  21981. if (index !== -1) {
  21982. this.animations.splice(index, 1);
  21983. }
  21984. return index;
  21985. };
  21986. ;
  21987. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21988. var index = this.multiMaterials.indexOf(toRemove);
  21989. if (index !== -1) {
  21990. this.multiMaterials.splice(index, 1);
  21991. }
  21992. return index;
  21993. };
  21994. ;
  21995. Scene.prototype.removeMaterial = function (toRemove) {
  21996. var index = this.materials.indexOf(toRemove);
  21997. if (index !== -1) {
  21998. this.materials.splice(index, 1);
  21999. }
  22000. return index;
  22001. };
  22002. ;
  22003. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22004. var index = this.lensFlareSystems.indexOf(toRemove);
  22005. if (index !== -1) {
  22006. this.lensFlareSystems.splice(index, 1);
  22007. }
  22008. return index;
  22009. };
  22010. ;
  22011. Scene.prototype.removeActionManager = function (toRemove) {
  22012. var index = this._actionManagers.indexOf(toRemove);
  22013. if (index !== -1) {
  22014. this._actionManagers.splice(index, 1);
  22015. }
  22016. return index;
  22017. };
  22018. ;
  22019. Scene.prototype.addLight = function (newLight) {
  22020. this.lights.push(newLight);
  22021. this.sortLightsByPriority();
  22022. // Add light to all meshes (To support if the light is removed and then readded)
  22023. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22024. var mesh = _a[_i];
  22025. if (mesh._lightSources.indexOf(newLight) === -1) {
  22026. mesh._lightSources.push(newLight);
  22027. mesh._resyncLightSources();
  22028. }
  22029. }
  22030. this.onNewLightAddedObservable.notifyObservers(newLight);
  22031. };
  22032. Scene.prototype.sortLightsByPriority = function () {
  22033. if (this.requireLightSorting) {
  22034. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22035. }
  22036. };
  22037. Scene.prototype.addCamera = function (newCamera) {
  22038. this.cameras.push(newCamera);
  22039. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22040. };
  22041. Scene.prototype.addSkeleton = function (newSkeleton) {
  22042. this.skeletons.push(newSkeleton);
  22043. };
  22044. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22045. this.particleSystems.push(newParticleSystem);
  22046. };
  22047. Scene.prototype.addAnimation = function (newAnimation) {
  22048. this.animations.push(newAnimation);
  22049. };
  22050. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22051. this.multiMaterials.push(newMultiMaterial);
  22052. };
  22053. Scene.prototype.addMaterial = function (newMaterial) {
  22054. this.materials.push(newMaterial);
  22055. };
  22056. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22057. this.morphTargetManagers.push(newMorphTargetManager);
  22058. };
  22059. Scene.prototype.addGeometry = function (newGeometrie) {
  22060. this._geometries.push(newGeometrie);
  22061. };
  22062. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22063. this.lensFlareSystems.push(newLensFlareSystem);
  22064. };
  22065. Scene.prototype.addActionManager = function (newActionManager) {
  22066. this._actionManagers.push(newActionManager);
  22067. };
  22068. /**
  22069. * Switch active camera
  22070. * @param {Camera} newCamera - new active camera
  22071. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22072. */
  22073. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22074. if (attachControl === void 0) { attachControl = true; }
  22075. var canvas = this._engine.getRenderingCanvas();
  22076. if (!canvas) {
  22077. return;
  22078. }
  22079. if (this.activeCamera) {
  22080. this.activeCamera.detachControl(canvas);
  22081. }
  22082. this.activeCamera = newCamera;
  22083. if (attachControl) {
  22084. newCamera.attachControl(canvas);
  22085. }
  22086. };
  22087. /**
  22088. * sets the active camera of the scene using its ID
  22089. * @param {string} id - the camera's ID
  22090. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22091. * @see activeCamera
  22092. */
  22093. Scene.prototype.setActiveCameraByID = function (id) {
  22094. var camera = this.getCameraByID(id);
  22095. if (camera) {
  22096. this.activeCamera = camera;
  22097. return camera;
  22098. }
  22099. return null;
  22100. };
  22101. /**
  22102. * sets the active camera of the scene using its name
  22103. * @param {string} name - the camera's name
  22104. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22105. * @see activeCamera
  22106. */
  22107. Scene.prototype.setActiveCameraByName = function (name) {
  22108. var camera = this.getCameraByName(name);
  22109. if (camera) {
  22110. this.activeCamera = camera;
  22111. return camera;
  22112. }
  22113. return null;
  22114. };
  22115. /**
  22116. * get an animation group using its name
  22117. * @param {string} the material's name
  22118. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22119. */
  22120. Scene.prototype.getAnimationGroupByName = function (name) {
  22121. for (var index = 0; index < this.animationGroups.length; index++) {
  22122. if (this.animationGroups[index].name === name) {
  22123. return this.animationGroups[index];
  22124. }
  22125. }
  22126. return null;
  22127. };
  22128. /**
  22129. * get a material using its id
  22130. * @param {string} the material's ID
  22131. * @return {BABYLON.Material|null} the material or null if none found.
  22132. */
  22133. Scene.prototype.getMaterialByID = function (id) {
  22134. for (var index = 0; index < this.materials.length; index++) {
  22135. if (this.materials[index].id === id) {
  22136. return this.materials[index];
  22137. }
  22138. }
  22139. return null;
  22140. };
  22141. /**
  22142. * get a material using its name
  22143. * @param {string} the material's name
  22144. * @return {BABYLON.Material|null} the material or null if none found.
  22145. */
  22146. Scene.prototype.getMaterialByName = function (name) {
  22147. for (var index = 0; index < this.materials.length; index++) {
  22148. if (this.materials[index].name === name) {
  22149. return this.materials[index];
  22150. }
  22151. }
  22152. return null;
  22153. };
  22154. Scene.prototype.getLensFlareSystemByName = function (name) {
  22155. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22156. if (this.lensFlareSystems[index].name === name) {
  22157. return this.lensFlareSystems[index];
  22158. }
  22159. }
  22160. return null;
  22161. };
  22162. Scene.prototype.getLensFlareSystemByID = function (id) {
  22163. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22164. if (this.lensFlareSystems[index].id === id) {
  22165. return this.lensFlareSystems[index];
  22166. }
  22167. }
  22168. return null;
  22169. };
  22170. Scene.prototype.getCameraByID = function (id) {
  22171. for (var index = 0; index < this.cameras.length; index++) {
  22172. if (this.cameras[index].id === id) {
  22173. return this.cameras[index];
  22174. }
  22175. }
  22176. return null;
  22177. };
  22178. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22179. for (var index = 0; index < this.cameras.length; index++) {
  22180. if (this.cameras[index].uniqueId === uniqueId) {
  22181. return this.cameras[index];
  22182. }
  22183. }
  22184. return null;
  22185. };
  22186. /**
  22187. * get a camera using its name
  22188. * @param {string} the camera's name
  22189. * @return {BABYLON.Camera|null} the camera or null if none found.
  22190. */
  22191. Scene.prototype.getCameraByName = function (name) {
  22192. for (var index = 0; index < this.cameras.length; index++) {
  22193. if (this.cameras[index].name === name) {
  22194. return this.cameras[index];
  22195. }
  22196. }
  22197. return null;
  22198. };
  22199. /**
  22200. * get a bone using its id
  22201. * @param {string} the bone's id
  22202. * @return {BABYLON.Bone|null} the bone or null if not found
  22203. */
  22204. Scene.prototype.getBoneByID = function (id) {
  22205. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22206. var skeleton = this.skeletons[skeletonIndex];
  22207. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22208. if (skeleton.bones[boneIndex].id === id) {
  22209. return skeleton.bones[boneIndex];
  22210. }
  22211. }
  22212. }
  22213. return null;
  22214. };
  22215. /**
  22216. * get a bone using its id
  22217. * @param {string} the bone's name
  22218. * @return {BABYLON.Bone|null} the bone or null if not found
  22219. */
  22220. Scene.prototype.getBoneByName = function (name) {
  22221. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22222. var skeleton = this.skeletons[skeletonIndex];
  22223. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22224. if (skeleton.bones[boneIndex].name === name) {
  22225. return skeleton.bones[boneIndex];
  22226. }
  22227. }
  22228. }
  22229. return null;
  22230. };
  22231. /**
  22232. * get a light node using its name
  22233. * @param {string} the light's name
  22234. * @return {BABYLON.Light|null} the light or null if none found.
  22235. */
  22236. Scene.prototype.getLightByName = function (name) {
  22237. for (var index = 0; index < this.lights.length; index++) {
  22238. if (this.lights[index].name === name) {
  22239. return this.lights[index];
  22240. }
  22241. }
  22242. return null;
  22243. };
  22244. /**
  22245. * get a light node using its ID
  22246. * @param {string} the light's id
  22247. * @return {BABYLON.Light|null} the light or null if none found.
  22248. */
  22249. Scene.prototype.getLightByID = function (id) {
  22250. for (var index = 0; index < this.lights.length; index++) {
  22251. if (this.lights[index].id === id) {
  22252. return this.lights[index];
  22253. }
  22254. }
  22255. return null;
  22256. };
  22257. /**
  22258. * get a light node using its scene-generated unique ID
  22259. * @param {number} the light's unique id
  22260. * @return {BABYLON.Light|null} the light or null if none found.
  22261. */
  22262. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22263. for (var index = 0; index < this.lights.length; index++) {
  22264. if (this.lights[index].uniqueId === uniqueId) {
  22265. return this.lights[index];
  22266. }
  22267. }
  22268. return null;
  22269. };
  22270. /**
  22271. * get a particle system by id
  22272. * @param id {number} the particle system id
  22273. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22274. */
  22275. Scene.prototype.getParticleSystemByID = function (id) {
  22276. for (var index = 0; index < this.particleSystems.length; index++) {
  22277. if (this.particleSystems[index].id === id) {
  22278. return this.particleSystems[index];
  22279. }
  22280. }
  22281. return null;
  22282. };
  22283. /**
  22284. * get a geometry using its ID
  22285. * @param {string} the geometry's id
  22286. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22287. */
  22288. Scene.prototype.getGeometryByID = function (id) {
  22289. for (var index = 0; index < this._geometries.length; index++) {
  22290. if (this._geometries[index].id === id) {
  22291. return this._geometries[index];
  22292. }
  22293. }
  22294. return null;
  22295. };
  22296. /**
  22297. * add a new geometry to this scene.
  22298. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22299. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22300. * @return {boolean} was the geometry added or not
  22301. */
  22302. Scene.prototype.pushGeometry = function (geometry, force) {
  22303. if (!force && this.getGeometryByID(geometry.id)) {
  22304. return false;
  22305. }
  22306. this._geometries.push(geometry);
  22307. //notify the collision coordinator
  22308. if (this.collisionCoordinator) {
  22309. this.collisionCoordinator.onGeometryAdded(geometry);
  22310. }
  22311. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22312. return true;
  22313. };
  22314. /**
  22315. * Removes an existing geometry
  22316. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22317. * @return {boolean} was the geometry removed or not
  22318. */
  22319. Scene.prototype.removeGeometry = function (geometry) {
  22320. var index = this._geometries.indexOf(geometry);
  22321. if (index > -1) {
  22322. this._geometries.splice(index, 1);
  22323. //notify the collision coordinator
  22324. if (this.collisionCoordinator) {
  22325. this.collisionCoordinator.onGeometryDeleted(geometry);
  22326. }
  22327. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22328. return true;
  22329. }
  22330. return false;
  22331. };
  22332. Scene.prototype.getGeometries = function () {
  22333. return this._geometries;
  22334. };
  22335. /**
  22336. * Get the first added mesh found of a given ID
  22337. * @param {string} id - the id to search for
  22338. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22339. */
  22340. Scene.prototype.getMeshByID = function (id) {
  22341. for (var index = 0; index < this.meshes.length; index++) {
  22342. if (this.meshes[index].id === id) {
  22343. return this.meshes[index];
  22344. }
  22345. }
  22346. return null;
  22347. };
  22348. Scene.prototype.getMeshesByID = function (id) {
  22349. return this.meshes.filter(function (m) {
  22350. return m.id === id;
  22351. });
  22352. };
  22353. /**
  22354. * Get the first added transform node found of a given ID
  22355. * @param {string} id - the id to search for
  22356. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22357. */
  22358. Scene.prototype.getTransformNodeByID = function (id) {
  22359. for (var index = 0; index < this.transformNodes.length; index++) {
  22360. if (this.transformNodes[index].id === id) {
  22361. return this.transformNodes[index];
  22362. }
  22363. }
  22364. return null;
  22365. };
  22366. Scene.prototype.getTransformNodesByID = function (id) {
  22367. return this.transformNodes.filter(function (m) {
  22368. return m.id === id;
  22369. });
  22370. };
  22371. /**
  22372. * Get a mesh with its auto-generated unique id
  22373. * @param {number} uniqueId - the unique id to search for
  22374. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22375. */
  22376. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22377. for (var index = 0; index < this.meshes.length; index++) {
  22378. if (this.meshes[index].uniqueId === uniqueId) {
  22379. return this.meshes[index];
  22380. }
  22381. }
  22382. return null;
  22383. };
  22384. /**
  22385. * Get a the last added mesh found of a given ID
  22386. * @param {string} id - the id to search for
  22387. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22388. */
  22389. Scene.prototype.getLastMeshByID = function (id) {
  22390. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22391. if (this.meshes[index].id === id) {
  22392. return this.meshes[index];
  22393. }
  22394. }
  22395. return null;
  22396. };
  22397. /**
  22398. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22399. * @param {string} id - the id to search for
  22400. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22401. */
  22402. Scene.prototype.getLastEntryByID = function (id) {
  22403. var index;
  22404. for (index = this.meshes.length - 1; index >= 0; index--) {
  22405. if (this.meshes[index].id === id) {
  22406. return this.meshes[index];
  22407. }
  22408. }
  22409. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22410. if (this.transformNodes[index].id === id) {
  22411. return this.transformNodes[index];
  22412. }
  22413. }
  22414. for (index = this.cameras.length - 1; index >= 0; index--) {
  22415. if (this.cameras[index].id === id) {
  22416. return this.cameras[index];
  22417. }
  22418. }
  22419. for (index = this.lights.length - 1; index >= 0; index--) {
  22420. if (this.lights[index].id === id) {
  22421. return this.lights[index];
  22422. }
  22423. }
  22424. return null;
  22425. };
  22426. Scene.prototype.getNodeByID = function (id) {
  22427. var mesh = this.getMeshByID(id);
  22428. if (mesh) {
  22429. return mesh;
  22430. }
  22431. var light = this.getLightByID(id);
  22432. if (light) {
  22433. return light;
  22434. }
  22435. var camera = this.getCameraByID(id);
  22436. if (camera) {
  22437. return camera;
  22438. }
  22439. var bone = this.getBoneByID(id);
  22440. return bone;
  22441. };
  22442. Scene.prototype.getNodeByName = function (name) {
  22443. var mesh = this.getMeshByName(name);
  22444. if (mesh) {
  22445. return mesh;
  22446. }
  22447. var light = this.getLightByName(name);
  22448. if (light) {
  22449. return light;
  22450. }
  22451. var camera = this.getCameraByName(name);
  22452. if (camera) {
  22453. return camera;
  22454. }
  22455. var bone = this.getBoneByName(name);
  22456. return bone;
  22457. };
  22458. Scene.prototype.getMeshByName = function (name) {
  22459. for (var index = 0; index < this.meshes.length; index++) {
  22460. if (this.meshes[index].name === name) {
  22461. return this.meshes[index];
  22462. }
  22463. }
  22464. return null;
  22465. };
  22466. Scene.prototype.getTransformNodeByName = function (name) {
  22467. for (var index = 0; index < this.transformNodes.length; index++) {
  22468. if (this.transformNodes[index].name === name) {
  22469. return this.transformNodes[index];
  22470. }
  22471. }
  22472. return null;
  22473. };
  22474. Scene.prototype.getSoundByName = function (name) {
  22475. var index;
  22476. if (BABYLON.AudioEngine) {
  22477. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22478. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22479. return this.mainSoundTrack.soundCollection[index];
  22480. }
  22481. }
  22482. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22483. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22484. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22485. return this.soundTracks[sdIndex].soundCollection[index];
  22486. }
  22487. }
  22488. }
  22489. }
  22490. return null;
  22491. };
  22492. Scene.prototype.getLastSkeletonByID = function (id) {
  22493. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22494. if (this.skeletons[index].id === id) {
  22495. return this.skeletons[index];
  22496. }
  22497. }
  22498. return null;
  22499. };
  22500. Scene.prototype.getSkeletonById = function (id) {
  22501. for (var index = 0; index < this.skeletons.length; index++) {
  22502. if (this.skeletons[index].id === id) {
  22503. return this.skeletons[index];
  22504. }
  22505. }
  22506. return null;
  22507. };
  22508. Scene.prototype.getSkeletonByName = function (name) {
  22509. for (var index = 0; index < this.skeletons.length; index++) {
  22510. if (this.skeletons[index].name === name) {
  22511. return this.skeletons[index];
  22512. }
  22513. }
  22514. return null;
  22515. };
  22516. Scene.prototype.getMorphTargetManagerById = function (id) {
  22517. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22518. if (this.morphTargetManagers[index].uniqueId === id) {
  22519. return this.morphTargetManagers[index];
  22520. }
  22521. }
  22522. return null;
  22523. };
  22524. Scene.prototype.isActiveMesh = function (mesh) {
  22525. return (this._activeMeshes.indexOf(mesh) !== -1);
  22526. };
  22527. /**
  22528. * Return a the first highlight layer of the scene with a given name.
  22529. * @param name The name of the highlight layer to look for.
  22530. * @return The highlight layer if found otherwise null.
  22531. */
  22532. Scene.prototype.getHighlightLayerByName = function (name) {
  22533. for (var index = 0; index < this.highlightLayers.length; index++) {
  22534. if (this.highlightLayers[index].name === name) {
  22535. return this.highlightLayers[index];
  22536. }
  22537. }
  22538. return null;
  22539. };
  22540. Object.defineProperty(Scene.prototype, "uid", {
  22541. /**
  22542. * Return a unique id as a string which can serve as an identifier for the scene
  22543. */
  22544. get: function () {
  22545. if (!this._uid) {
  22546. this._uid = BABYLON.Tools.RandomId();
  22547. }
  22548. return this._uid;
  22549. },
  22550. enumerable: true,
  22551. configurable: true
  22552. });
  22553. /**
  22554. * Add an externaly attached data from its key.
  22555. * This method call will fail and return false, if such key already exists.
  22556. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22557. * @param key the unique key that identifies the data
  22558. * @param data the data object to associate to the key for this Engine instance
  22559. * @return true if no such key were already present and the data was added successfully, false otherwise
  22560. */
  22561. Scene.prototype.addExternalData = function (key, data) {
  22562. if (!this._externalData) {
  22563. this._externalData = new BABYLON.StringDictionary();
  22564. }
  22565. return this._externalData.add(key, data);
  22566. };
  22567. /**
  22568. * Get an externaly attached data from its key
  22569. * @param key the unique key that identifies the data
  22570. * @return the associated data, if present (can be null), or undefined if not present
  22571. */
  22572. Scene.prototype.getExternalData = function (key) {
  22573. if (!this._externalData) {
  22574. return null;
  22575. }
  22576. return this._externalData.get(key);
  22577. };
  22578. /**
  22579. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22580. * @param key the unique key that identifies the data
  22581. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22582. * @return the associated data, can be null if the factory returned null.
  22583. */
  22584. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22585. if (!this._externalData) {
  22586. this._externalData = new BABYLON.StringDictionary();
  22587. }
  22588. return this._externalData.getOrAddWithFactory(key, factory);
  22589. };
  22590. /**
  22591. * Remove an externaly attached data from the Engine instance
  22592. * @param key the unique key that identifies the data
  22593. * @return true if the data was successfully removed, false if it doesn't exist
  22594. */
  22595. Scene.prototype.removeExternalData = function (key) {
  22596. return this._externalData.remove(key);
  22597. };
  22598. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22599. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22600. if (mesh.showSubMeshesBoundingBox) {
  22601. var boundingInfo = subMesh.getBoundingInfo();
  22602. if (boundingInfo !== null && boundingInfo !== undefined) {
  22603. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22604. }
  22605. }
  22606. var material = subMesh.getMaterial();
  22607. if (material !== null && material !== undefined) {
  22608. // Render targets
  22609. if (material.getRenderTargetTextures !== undefined) {
  22610. if (this._processedMaterials.indexOf(material) === -1) {
  22611. this._processedMaterials.push(material);
  22612. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22613. }
  22614. }
  22615. // Dispatch
  22616. this._activeIndices.addCount(subMesh.indexCount, false);
  22617. this._renderingManager.dispatch(subMesh, mesh, material);
  22618. }
  22619. }
  22620. };
  22621. Scene.prototype._isInIntermediateRendering = function () {
  22622. return this._intermediateRendering;
  22623. };
  22624. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22625. this._activeMeshCandidateProvider = provider;
  22626. };
  22627. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22628. return this._activeMeshCandidateProvider;
  22629. };
  22630. /**
  22631. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22632. */
  22633. Scene.prototype.freezeActiveMeshes = function () {
  22634. this._evaluateActiveMeshes();
  22635. this._activeMeshesFrozen = true;
  22636. return this;
  22637. };
  22638. /**
  22639. * Use this function to restart evaluating active meshes on every frame
  22640. */
  22641. Scene.prototype.unfreezeActiveMeshes = function () {
  22642. this._activeMeshesFrozen = false;
  22643. return this;
  22644. };
  22645. Scene.prototype._evaluateActiveMeshes = function () {
  22646. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22647. return;
  22648. }
  22649. if (!this.activeCamera) {
  22650. return;
  22651. }
  22652. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22653. this.activeCamera._activeMeshes.reset();
  22654. this._activeMeshes.reset();
  22655. this._renderingManager.reset();
  22656. this._processedMaterials.reset();
  22657. this._activeParticleSystems.reset();
  22658. this._activeSkeletons.reset();
  22659. this._softwareSkinnedMeshes.reset();
  22660. if (this._boundingBoxRenderer) {
  22661. this._boundingBoxRenderer.reset();
  22662. }
  22663. // Meshes
  22664. var meshes;
  22665. var len;
  22666. var checkIsEnabled = true;
  22667. // Determine mesh candidates
  22668. if (this._activeMeshCandidateProvider !== undefined) {
  22669. // Use _activeMeshCandidateProvider
  22670. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22671. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22672. if (meshes !== undefined) {
  22673. len = meshes.length;
  22674. }
  22675. else {
  22676. len = 0;
  22677. }
  22678. }
  22679. else if (this._selectionOctree !== undefined) {
  22680. // Octree
  22681. var selection = this._selectionOctree.select(this._frustumPlanes);
  22682. meshes = selection.data;
  22683. len = selection.length;
  22684. }
  22685. else {
  22686. // Full scene traversal
  22687. len = this.meshes.length;
  22688. meshes = this.meshes;
  22689. }
  22690. // Check each mesh
  22691. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22692. mesh = meshes[meshIndex];
  22693. if (mesh.isBlocked) {
  22694. continue;
  22695. }
  22696. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22697. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22698. continue;
  22699. }
  22700. mesh.computeWorldMatrix();
  22701. // Intersections
  22702. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22703. this._meshesForIntersections.pushNoDuplicate(mesh);
  22704. }
  22705. // Switch to current LOD
  22706. meshLOD = mesh.getLOD(this.activeCamera);
  22707. if (meshLOD === undefined || meshLOD === null) {
  22708. continue;
  22709. }
  22710. mesh._preActivate();
  22711. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22712. this._activeMeshes.push(mesh);
  22713. this.activeCamera._activeMeshes.push(mesh);
  22714. mesh._activate(this._renderId);
  22715. if (meshLOD !== mesh) {
  22716. meshLOD._activate(this._renderId);
  22717. }
  22718. this._activeMesh(mesh, meshLOD);
  22719. }
  22720. }
  22721. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22722. // Particle systems
  22723. if (this.particlesEnabled) {
  22724. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22725. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22726. var particleSystem = this.particleSystems[particleIndex];
  22727. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22728. continue;
  22729. }
  22730. var emitter = particleSystem.emitter;
  22731. if (!emitter.position || emitter.isEnabled()) {
  22732. this._activeParticleSystems.push(particleSystem);
  22733. particleSystem.animate();
  22734. this._renderingManager.dispatchParticles(particleSystem);
  22735. }
  22736. }
  22737. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22738. }
  22739. };
  22740. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22741. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22742. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22743. mesh.skeleton.prepare();
  22744. }
  22745. if (!mesh.computeBonesUsingShaders) {
  22746. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22747. }
  22748. }
  22749. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22750. var boundingInfo = sourceMesh.getBoundingInfo();
  22751. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22752. }
  22753. if (mesh !== undefined && mesh !== null
  22754. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22755. // Submeshes Octrees
  22756. var len;
  22757. var subMeshes;
  22758. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22759. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22760. len = intersections.length;
  22761. subMeshes = intersections.data;
  22762. }
  22763. else {
  22764. subMeshes = mesh.subMeshes;
  22765. len = subMeshes.length;
  22766. }
  22767. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22768. subMesh = subMeshes[subIndex];
  22769. this._evaluateSubMesh(subMesh, mesh);
  22770. }
  22771. }
  22772. };
  22773. Scene.prototype.updateTransformMatrix = function (force) {
  22774. if (!this.activeCamera) {
  22775. return;
  22776. }
  22777. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22778. };
  22779. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22780. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22781. };
  22782. Scene.prototype._renderForCamera = function (camera) {
  22783. if (camera && camera._skipRendering) {
  22784. return;
  22785. }
  22786. var engine = this._engine;
  22787. this.activeCamera = camera;
  22788. if (!this.activeCamera)
  22789. throw new Error("Active camera not set");
  22790. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22791. // Viewport
  22792. engine.setViewport(this.activeCamera.viewport);
  22793. // Camera
  22794. this.resetCachedMaterial();
  22795. this._renderId++;
  22796. this.activeCamera.update();
  22797. this.updateTransformMatrix();
  22798. if (camera._alternateCamera) {
  22799. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22800. this._alternateRendering = true;
  22801. }
  22802. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22803. // Meshes
  22804. this._evaluateActiveMeshes();
  22805. // Software skinning
  22806. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22807. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22808. mesh.applySkeleton(mesh.skeleton);
  22809. }
  22810. // Render targets
  22811. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22812. var needsRestoreFrameBuffer = false;
  22813. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22814. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22815. }
  22816. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22817. this._intermediateRendering = true;
  22818. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22819. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22820. var renderTarget = this._renderTargets.data[renderIndex];
  22821. if (renderTarget._shouldRender()) {
  22822. this._renderId++;
  22823. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22824. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22825. }
  22826. }
  22827. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22828. this._intermediateRendering = false;
  22829. this._renderId++;
  22830. needsRestoreFrameBuffer = true; // Restore back buffer
  22831. }
  22832. // Render HighlightLayer Texture
  22833. var stencilState = this._engine.getStencilBuffer();
  22834. var renderhighlights = false;
  22835. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22836. this._intermediateRendering = true;
  22837. for (var i = 0; i < this.highlightLayers.length; i++) {
  22838. var highlightLayer = this.highlightLayers[i];
  22839. if (highlightLayer.shouldRender() &&
  22840. (!highlightLayer.camera ||
  22841. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22842. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22843. renderhighlights = true;
  22844. var renderTarget = highlightLayer._mainTexture;
  22845. if (renderTarget._shouldRender()) {
  22846. this._renderId++;
  22847. renderTarget.render(false, false);
  22848. needsRestoreFrameBuffer = true;
  22849. }
  22850. }
  22851. }
  22852. this._intermediateRendering = false;
  22853. this._renderId++;
  22854. }
  22855. if (needsRestoreFrameBuffer) {
  22856. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22857. }
  22858. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22859. // Prepare Frame
  22860. this.postProcessManager._prepareFrame();
  22861. // Backgrounds
  22862. var layerIndex;
  22863. var layer;
  22864. if (this.layers.length) {
  22865. engine.setDepthBuffer(false);
  22866. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22867. layer = this.layers[layerIndex];
  22868. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22869. layer.render();
  22870. }
  22871. }
  22872. engine.setDepthBuffer(true);
  22873. }
  22874. // Activate HighlightLayer stencil
  22875. if (renderhighlights) {
  22876. this._engine.setStencilBuffer(true);
  22877. }
  22878. // Render
  22879. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22880. this._renderingManager.render(null, null, true, true);
  22881. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22882. // Restore HighlightLayer stencil
  22883. if (renderhighlights) {
  22884. this._engine.setStencilBuffer(stencilState);
  22885. }
  22886. // Bounding boxes
  22887. if (this._boundingBoxRenderer) {
  22888. this._boundingBoxRenderer.render();
  22889. }
  22890. // Lens flares
  22891. if (this.lensFlaresEnabled) {
  22892. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22893. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22894. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22895. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22896. lensFlareSystem.render();
  22897. }
  22898. }
  22899. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22900. }
  22901. // Foregrounds
  22902. if (this.layers.length) {
  22903. engine.setDepthBuffer(false);
  22904. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22905. layer = this.layers[layerIndex];
  22906. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22907. layer.render();
  22908. }
  22909. }
  22910. engine.setDepthBuffer(true);
  22911. }
  22912. // Highlight Layer
  22913. if (renderhighlights) {
  22914. engine.setDepthBuffer(false);
  22915. for (var i = 0; i < this.highlightLayers.length; i++) {
  22916. if (this.highlightLayers[i].shouldRender()) {
  22917. this.highlightLayers[i].render();
  22918. }
  22919. }
  22920. engine.setDepthBuffer(true);
  22921. }
  22922. // Finalize frame
  22923. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22924. // Reset some special arrays
  22925. this._renderTargets.reset();
  22926. this._alternateRendering = false;
  22927. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22928. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22929. };
  22930. Scene.prototype._processSubCameras = function (camera) {
  22931. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22932. this._renderForCamera(camera);
  22933. return;
  22934. }
  22935. // Update camera
  22936. if (this.activeCamera) {
  22937. this.activeCamera.update();
  22938. }
  22939. // rig cameras
  22940. for (var index = 0; index < camera._rigCameras.length; index++) {
  22941. this._renderForCamera(camera._rigCameras[index]);
  22942. }
  22943. this.activeCamera = camera;
  22944. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22945. };
  22946. Scene.prototype._checkIntersections = function () {
  22947. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22948. var sourceMesh = this._meshesForIntersections.data[index];
  22949. if (!sourceMesh.actionManager) {
  22950. continue;
  22951. }
  22952. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22953. var action = sourceMesh.actionManager.actions[actionIndex];
  22954. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22955. var parameters = action.getTriggerParameter();
  22956. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22957. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22958. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22959. if (areIntersecting && currentIntersectionInProgress === -1) {
  22960. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22961. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22962. sourceMesh._intersectionsInProgress.push(otherMesh);
  22963. }
  22964. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22965. sourceMesh._intersectionsInProgress.push(otherMesh);
  22966. }
  22967. }
  22968. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22969. //They intersected, and now they don't.
  22970. //is this trigger an exit trigger? execute an event.
  22971. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22972. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22973. }
  22974. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22975. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22976. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22977. }
  22978. }
  22979. }
  22980. }
  22981. }
  22982. };
  22983. Scene.prototype.render = function () {
  22984. if (this.isDisposed) {
  22985. return;
  22986. }
  22987. this._activeParticles.fetchNewFrame();
  22988. this._totalVertices.fetchNewFrame();
  22989. this._activeIndices.fetchNewFrame();
  22990. this._activeBones.fetchNewFrame();
  22991. this._meshesForIntersections.reset();
  22992. this.resetCachedMaterial();
  22993. this.onBeforeAnimationsObservable.notifyObservers(this);
  22994. // Actions
  22995. if (this.actionManager) {
  22996. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22997. }
  22998. //Simplification Queue
  22999. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23000. this.simplificationQueue.executeNext();
  23001. }
  23002. if (this._engine.isDeterministicLockStep()) {
  23003. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23004. var defaultFPS = (60.0 / 1000.0);
  23005. var defaultFrameTime = 1000 / 60; // frame time in MS
  23006. if (this._physicsEngine) {
  23007. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23008. }
  23009. var stepsTaken = 0;
  23010. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23011. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23012. internalSteps = Math.min(internalSteps, maxSubSteps);
  23013. do {
  23014. this.onBeforeStepObservable.notifyObservers(this);
  23015. // Animations
  23016. this._animationRatio = defaultFrameTime * defaultFPS;
  23017. this._animate();
  23018. this.onAfterAnimationsObservable.notifyObservers(this);
  23019. // Physics
  23020. if (this._physicsEngine) {
  23021. this.onBeforePhysicsObservable.notifyObservers(this);
  23022. this._physicsEngine._step(defaultFrameTime / 1000);
  23023. this.onAfterPhysicsObservable.notifyObservers(this);
  23024. }
  23025. this.onAfterStepObservable.notifyObservers(this);
  23026. this._currentStepId++;
  23027. stepsTaken++;
  23028. deltaTime -= defaultFrameTime;
  23029. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23030. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23031. }
  23032. else {
  23033. // Animations
  23034. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23035. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23036. this._animate();
  23037. this.onAfterAnimationsObservable.notifyObservers(this);
  23038. // Physics
  23039. if (this._physicsEngine) {
  23040. this.onBeforePhysicsObservable.notifyObservers(this);
  23041. this._physicsEngine._step(deltaTime / 1000.0);
  23042. this.onAfterPhysicsObservable.notifyObservers(this);
  23043. }
  23044. }
  23045. // update gamepad manager
  23046. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23047. this._gamepadManager._checkGamepadsStatus();
  23048. }
  23049. // Before render
  23050. this.onBeforeRenderObservable.notifyObservers(this);
  23051. // Customs render targets
  23052. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23053. var engine = this.getEngine();
  23054. var currentActiveCamera = this.activeCamera;
  23055. if (this.renderTargetsEnabled) {
  23056. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23057. this._intermediateRendering = true;
  23058. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23059. var renderTarget = this.customRenderTargets[customIndex];
  23060. if (renderTarget._shouldRender()) {
  23061. this._renderId++;
  23062. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23063. if (!this.activeCamera)
  23064. throw new Error("Active camera not set");
  23065. // Viewport
  23066. engine.setViewport(this.activeCamera.viewport);
  23067. // Camera
  23068. this.updateTransformMatrix();
  23069. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23070. }
  23071. }
  23072. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23073. this._intermediateRendering = false;
  23074. this._renderId++;
  23075. }
  23076. // Restore back buffer
  23077. if (this.customRenderTargets.length > 0) {
  23078. engine.restoreDefaultFramebuffer();
  23079. }
  23080. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23081. this.activeCamera = currentActiveCamera;
  23082. // Procedural textures
  23083. if (this.proceduralTexturesEnabled) {
  23084. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23085. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23086. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23087. if (proceduralTexture._shouldRender()) {
  23088. proceduralTexture.render();
  23089. }
  23090. }
  23091. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23092. }
  23093. // Clear
  23094. if (this.autoClearDepthAndStencil || this.autoClear) {
  23095. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23096. }
  23097. // Shadows
  23098. if (this.shadowsEnabled) {
  23099. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23100. var light = this.lights[lightIndex];
  23101. var shadowGenerator = light.getShadowGenerator();
  23102. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23103. var shadowMap = (shadowGenerator.getShadowMap());
  23104. if (this.textures.indexOf(shadowMap) !== -1) {
  23105. this._renderTargets.push(shadowMap);
  23106. }
  23107. }
  23108. }
  23109. }
  23110. // Depth renderer
  23111. if (this._depthRenderer) {
  23112. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23113. }
  23114. // Geometry renderer
  23115. if (this._geometryBufferRenderer) {
  23116. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23117. }
  23118. // RenderPipeline
  23119. if (this._postProcessRenderPipelineManager) {
  23120. this._postProcessRenderPipelineManager.update();
  23121. }
  23122. // Multi-cameras?
  23123. if (this.activeCameras.length > 0) {
  23124. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23125. if (cameraIndex > 0) {
  23126. this._engine.clear(null, false, true, true);
  23127. }
  23128. this._processSubCameras(this.activeCameras[cameraIndex]);
  23129. }
  23130. }
  23131. else {
  23132. if (!this.activeCamera) {
  23133. throw new Error("No camera defined");
  23134. }
  23135. this._processSubCameras(this.activeCamera);
  23136. }
  23137. // Intersection checks
  23138. this._checkIntersections();
  23139. // Update the audio listener attached to the camera
  23140. if (BABYLON.AudioEngine) {
  23141. this._updateAudioParameters();
  23142. }
  23143. // After render
  23144. if (this.afterRender) {
  23145. this.afterRender();
  23146. }
  23147. this.onAfterRenderObservable.notifyObservers(this);
  23148. // Cleaning
  23149. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23150. var data = this._toBeDisposed.data[index];
  23151. if (data) {
  23152. data.dispose();
  23153. }
  23154. this._toBeDisposed[index] = null;
  23155. }
  23156. this._toBeDisposed.reset();
  23157. if (this.dumpNextRenderTargets) {
  23158. this.dumpNextRenderTargets = false;
  23159. }
  23160. this._activeBones.addCount(0, true);
  23161. this._activeIndices.addCount(0, true);
  23162. this._activeParticles.addCount(0, true);
  23163. };
  23164. Scene.prototype._updateAudioParameters = function () {
  23165. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23166. return;
  23167. }
  23168. var listeningCamera;
  23169. var audioEngine = BABYLON.Engine.audioEngine;
  23170. if (this.activeCameras.length > 0) {
  23171. listeningCamera = this.activeCameras[0];
  23172. }
  23173. else {
  23174. listeningCamera = this.activeCamera;
  23175. }
  23176. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23177. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23178. // for VR cameras
  23179. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23180. listeningCamera = listeningCamera.rigCameras[0];
  23181. }
  23182. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23183. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23184. cameraDirection.normalize();
  23185. // To avoid some errors on GearVR
  23186. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23187. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23188. }
  23189. var i;
  23190. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23191. var sound = this.mainSoundTrack.soundCollection[i];
  23192. if (sound.useCustomAttenuation) {
  23193. sound.updateDistanceFromListener();
  23194. }
  23195. }
  23196. for (i = 0; i < this.soundTracks.length; i++) {
  23197. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23198. sound = this.soundTracks[i].soundCollection[j];
  23199. if (sound.useCustomAttenuation) {
  23200. sound.updateDistanceFromListener();
  23201. }
  23202. }
  23203. }
  23204. }
  23205. };
  23206. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23207. // Audio
  23208. get: function () {
  23209. return this._audioEnabled;
  23210. },
  23211. set: function (value) {
  23212. this._audioEnabled = value;
  23213. if (BABYLON.AudioEngine) {
  23214. if (this._audioEnabled) {
  23215. this._enableAudio();
  23216. }
  23217. else {
  23218. this._disableAudio();
  23219. }
  23220. }
  23221. },
  23222. enumerable: true,
  23223. configurable: true
  23224. });
  23225. Scene.prototype._disableAudio = function () {
  23226. var i;
  23227. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23228. this.mainSoundTrack.soundCollection[i].pause();
  23229. }
  23230. for (i = 0; i < this.soundTracks.length; i++) {
  23231. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23232. this.soundTracks[i].soundCollection[j].pause();
  23233. }
  23234. }
  23235. };
  23236. Scene.prototype._enableAudio = function () {
  23237. var i;
  23238. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23239. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23240. this.mainSoundTrack.soundCollection[i].play();
  23241. }
  23242. }
  23243. for (i = 0; i < this.soundTracks.length; i++) {
  23244. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23245. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23246. this.soundTracks[i].soundCollection[j].play();
  23247. }
  23248. }
  23249. }
  23250. };
  23251. Object.defineProperty(Scene.prototype, "headphone", {
  23252. get: function () {
  23253. return this._headphone;
  23254. },
  23255. set: function (value) {
  23256. this._headphone = value;
  23257. if (BABYLON.AudioEngine) {
  23258. if (this._headphone) {
  23259. this._switchAudioModeForHeadphones();
  23260. }
  23261. else {
  23262. this._switchAudioModeForNormalSpeakers();
  23263. }
  23264. }
  23265. },
  23266. enumerable: true,
  23267. configurable: true
  23268. });
  23269. Scene.prototype._switchAudioModeForHeadphones = function () {
  23270. this.mainSoundTrack.switchPanningModelToHRTF();
  23271. for (var i = 0; i < this.soundTracks.length; i++) {
  23272. this.soundTracks[i].switchPanningModelToHRTF();
  23273. }
  23274. };
  23275. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23276. this.mainSoundTrack.switchPanningModelToEqualPower();
  23277. for (var i = 0; i < this.soundTracks.length; i++) {
  23278. this.soundTracks[i].switchPanningModelToEqualPower();
  23279. }
  23280. };
  23281. Scene.prototype.enableDepthRenderer = function () {
  23282. if (this._depthRenderer) {
  23283. return this._depthRenderer;
  23284. }
  23285. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23286. return this._depthRenderer;
  23287. };
  23288. Scene.prototype.disableDepthRenderer = function () {
  23289. if (!this._depthRenderer) {
  23290. return;
  23291. }
  23292. this._depthRenderer.dispose();
  23293. this._depthRenderer = null;
  23294. };
  23295. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23296. if (ratio === void 0) { ratio = 1; }
  23297. if (this._geometryBufferRenderer) {
  23298. return this._geometryBufferRenderer;
  23299. }
  23300. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23301. if (!this._geometryBufferRenderer.isSupported) {
  23302. this._geometryBufferRenderer = null;
  23303. }
  23304. return this._geometryBufferRenderer;
  23305. };
  23306. Scene.prototype.disableGeometryBufferRenderer = function () {
  23307. if (!this._geometryBufferRenderer) {
  23308. return;
  23309. }
  23310. this._geometryBufferRenderer.dispose();
  23311. this._geometryBufferRenderer = null;
  23312. };
  23313. Scene.prototype.freezeMaterials = function () {
  23314. for (var i = 0; i < this.materials.length; i++) {
  23315. this.materials[i].freeze();
  23316. }
  23317. };
  23318. Scene.prototype.unfreezeMaterials = function () {
  23319. for (var i = 0; i < this.materials.length; i++) {
  23320. this.materials[i].unfreeze();
  23321. }
  23322. };
  23323. Scene.prototype.dispose = function () {
  23324. this.beforeRender = null;
  23325. this.afterRender = null;
  23326. this.skeletons = [];
  23327. this.morphTargetManagers = [];
  23328. this.importedMeshesFiles = new Array();
  23329. this.stopAllAnimations();
  23330. this.resetCachedMaterial();
  23331. if (this._depthRenderer) {
  23332. this._depthRenderer.dispose();
  23333. }
  23334. if (this._gamepadManager) {
  23335. this._gamepadManager.dispose();
  23336. this._gamepadManager = null;
  23337. }
  23338. // Smart arrays
  23339. if (this.activeCamera) {
  23340. this.activeCamera._activeMeshes.dispose();
  23341. this.activeCamera = null;
  23342. }
  23343. this._activeMeshes.dispose();
  23344. this._renderingManager.dispose();
  23345. this._processedMaterials.dispose();
  23346. this._activeParticleSystems.dispose();
  23347. this._activeSkeletons.dispose();
  23348. this._softwareSkinnedMeshes.dispose();
  23349. this._renderTargets.dispose();
  23350. if (this._boundingBoxRenderer) {
  23351. this._boundingBoxRenderer.dispose();
  23352. }
  23353. this._meshesForIntersections.dispose();
  23354. this._toBeDisposed.dispose();
  23355. // Abort active requests
  23356. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23357. var request = _a[_i];
  23358. request.abort();
  23359. }
  23360. // Debug layer
  23361. if (this._debugLayer) {
  23362. this._debugLayer.hide();
  23363. }
  23364. // Events
  23365. this.onDisposeObservable.notifyObservers(this);
  23366. this.onDisposeObservable.clear();
  23367. this.onBeforeRenderObservable.clear();
  23368. this.onAfterRenderObservable.clear();
  23369. this.OnBeforeRenderTargetsRenderObservable.clear();
  23370. this.OnAfterRenderTargetsRenderObservable.clear();
  23371. this.onAfterStepObservable.clear();
  23372. this.onBeforeStepObservable.clear();
  23373. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23374. this.onAfterActiveMeshesEvaluationObservable.clear();
  23375. this.onBeforeParticlesRenderingObservable.clear();
  23376. this.onAfterParticlesRenderingObservable.clear();
  23377. this.onBeforeSpritesRenderingObservable.clear();
  23378. this.onAfterSpritesRenderingObservable.clear();
  23379. this.onBeforeDrawPhaseObservable.clear();
  23380. this.onAfterDrawPhaseObservable.clear();
  23381. this.onBeforePhysicsObservable.clear();
  23382. this.onAfterPhysicsObservable.clear();
  23383. this.onBeforeAnimationsObservable.clear();
  23384. this.onAfterAnimationsObservable.clear();
  23385. this.onDataLoadedObservable.clear();
  23386. this.detachControl();
  23387. // Release sounds & sounds tracks
  23388. if (BABYLON.AudioEngine) {
  23389. this.disposeSounds();
  23390. }
  23391. // VR Helper
  23392. if (this.VRHelper) {
  23393. this.VRHelper.dispose();
  23394. }
  23395. // Detach cameras
  23396. var canvas = this._engine.getRenderingCanvas();
  23397. if (canvas) {
  23398. var index;
  23399. for (index = 0; index < this.cameras.length; index++) {
  23400. this.cameras[index].detachControl(canvas);
  23401. }
  23402. }
  23403. // Release animation groups
  23404. while (this.animationGroups.length) {
  23405. this.animationGroups[0].dispose();
  23406. }
  23407. // Release lights
  23408. while (this.lights.length) {
  23409. this.lights[0].dispose();
  23410. }
  23411. // Release meshes
  23412. while (this.meshes.length) {
  23413. this.meshes[0].dispose(true);
  23414. }
  23415. while (this.transformNodes.length) {
  23416. this.removeTransformNode(this.transformNodes[0]);
  23417. }
  23418. // Release cameras
  23419. while (this.cameras.length) {
  23420. this.cameras[0].dispose();
  23421. }
  23422. // Release materials
  23423. if (this.defaultMaterial) {
  23424. this.defaultMaterial.dispose();
  23425. }
  23426. while (this.multiMaterials.length) {
  23427. this.multiMaterials[0].dispose();
  23428. }
  23429. while (this.materials.length) {
  23430. this.materials[0].dispose();
  23431. }
  23432. // Release particles
  23433. while (this.particleSystems.length) {
  23434. this.particleSystems[0].dispose();
  23435. }
  23436. // Release sprites
  23437. while (this.spriteManagers.length) {
  23438. this.spriteManagers[0].dispose();
  23439. }
  23440. // Release postProcesses
  23441. while (this.postProcesses.length) {
  23442. this.postProcesses[0].dispose();
  23443. }
  23444. // Release layers
  23445. while (this.layers.length) {
  23446. this.layers[0].dispose();
  23447. }
  23448. while (this.highlightLayers.length) {
  23449. this.highlightLayers[0].dispose();
  23450. }
  23451. // Release textures
  23452. while (this.textures.length) {
  23453. this.textures[0].dispose();
  23454. }
  23455. // Release UBO
  23456. this._sceneUbo.dispose();
  23457. if (this._alternateSceneUbo) {
  23458. this._alternateSceneUbo.dispose();
  23459. }
  23460. // Post-processes
  23461. this.postProcessManager.dispose();
  23462. if (this._postProcessRenderPipelineManager) {
  23463. this._postProcessRenderPipelineManager.dispose();
  23464. }
  23465. // Physics
  23466. if (this._physicsEngine) {
  23467. this.disablePhysicsEngine();
  23468. }
  23469. // Remove from engine
  23470. index = this._engine.scenes.indexOf(this);
  23471. if (index > -1) {
  23472. this._engine.scenes.splice(index, 1);
  23473. }
  23474. this._engine.wipeCaches(true);
  23475. this._isDisposed = true;
  23476. };
  23477. Object.defineProperty(Scene.prototype, "isDisposed", {
  23478. get: function () {
  23479. return this._isDisposed;
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. // Release sounds & sounds tracks
  23485. Scene.prototype.disposeSounds = function () {
  23486. if (!this._mainSoundTrack) {
  23487. return;
  23488. }
  23489. this.mainSoundTrack.dispose();
  23490. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23491. this.soundTracks[scIndex].dispose();
  23492. }
  23493. };
  23494. // Octrees
  23495. Scene.prototype.getWorldExtends = function () {
  23496. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23497. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23498. for (var index = 0; index < this.meshes.length; index++) {
  23499. var mesh = this.meshes[index];
  23500. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23501. continue;
  23502. }
  23503. mesh.computeWorldMatrix(true);
  23504. var boundingInfo = mesh.getBoundingInfo();
  23505. var minBox = boundingInfo.boundingBox.minimumWorld;
  23506. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23507. BABYLON.Tools.CheckExtends(minBox, min, max);
  23508. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23509. }
  23510. return {
  23511. min: min,
  23512. max: max
  23513. };
  23514. };
  23515. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23516. if (maxCapacity === void 0) { maxCapacity = 64; }
  23517. if (maxDepth === void 0) { maxDepth = 2; }
  23518. if (!this._selectionOctree) {
  23519. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23520. }
  23521. var worldExtends = this.getWorldExtends();
  23522. // Update octree
  23523. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23524. return this._selectionOctree;
  23525. };
  23526. // Picking
  23527. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23528. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23529. var result = BABYLON.Ray.Zero();
  23530. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23531. return result;
  23532. };
  23533. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23534. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23535. var engine = this._engine;
  23536. if (!camera) {
  23537. if (!this.activeCamera)
  23538. throw new Error("Active camera not set");
  23539. camera = this.activeCamera;
  23540. }
  23541. var cameraViewport = camera.viewport;
  23542. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23543. // Moving coordinates to local viewport world
  23544. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23545. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23546. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23547. return this;
  23548. };
  23549. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23550. var result = BABYLON.Ray.Zero();
  23551. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23552. return result;
  23553. };
  23554. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23555. if (!BABYLON.PickingInfo) {
  23556. return this;
  23557. }
  23558. var engine = this._engine;
  23559. if (!camera) {
  23560. if (!this.activeCamera)
  23561. throw new Error("Active camera not set");
  23562. camera = this.activeCamera;
  23563. }
  23564. var cameraViewport = camera.viewport;
  23565. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23566. var identity = BABYLON.Matrix.Identity();
  23567. // Moving coordinates to local viewport world
  23568. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23569. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23570. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23571. return this;
  23572. };
  23573. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23574. if (!BABYLON.PickingInfo) {
  23575. return null;
  23576. }
  23577. var pickingInfo = null;
  23578. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23579. var mesh = this.meshes[meshIndex];
  23580. if (predicate) {
  23581. if (!predicate(mesh)) {
  23582. continue;
  23583. }
  23584. }
  23585. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23586. continue;
  23587. }
  23588. var world = mesh.getWorldMatrix();
  23589. var ray = rayFunction(world);
  23590. var result = mesh.intersects(ray, fastCheck);
  23591. if (!result || !result.hit)
  23592. continue;
  23593. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23594. continue;
  23595. pickingInfo = result;
  23596. if (fastCheck) {
  23597. break;
  23598. }
  23599. }
  23600. return pickingInfo || new BABYLON.PickingInfo();
  23601. };
  23602. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23603. if (!BABYLON.PickingInfo) {
  23604. return null;
  23605. }
  23606. var pickingInfos = new Array();
  23607. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23608. var mesh = this.meshes[meshIndex];
  23609. if (predicate) {
  23610. if (!predicate(mesh)) {
  23611. continue;
  23612. }
  23613. }
  23614. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23615. continue;
  23616. }
  23617. var world = mesh.getWorldMatrix();
  23618. var ray = rayFunction(world);
  23619. var result = mesh.intersects(ray, false);
  23620. if (!result || !result.hit)
  23621. continue;
  23622. pickingInfos.push(result);
  23623. }
  23624. return pickingInfos;
  23625. };
  23626. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23627. if (!BABYLON.PickingInfo) {
  23628. return null;
  23629. }
  23630. var pickingInfo = null;
  23631. if (!camera) {
  23632. if (!this.activeCamera) {
  23633. return null;
  23634. }
  23635. camera = this.activeCamera;
  23636. }
  23637. if (this.spriteManagers.length > 0) {
  23638. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23639. var spriteManager = this.spriteManagers[spriteIndex];
  23640. if (!spriteManager.isPickable) {
  23641. continue;
  23642. }
  23643. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23644. if (!result || !result.hit)
  23645. continue;
  23646. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23647. continue;
  23648. pickingInfo = result;
  23649. if (fastCheck) {
  23650. break;
  23651. }
  23652. }
  23653. }
  23654. return pickingInfo || new BABYLON.PickingInfo();
  23655. };
  23656. /** Launch a ray to try to pick a mesh in the scene
  23657. * @param x position on screen
  23658. * @param y position on screen
  23659. * @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
  23660. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23661. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23662. */
  23663. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23664. var _this = this;
  23665. if (!BABYLON.PickingInfo) {
  23666. return null;
  23667. }
  23668. return this._internalPick(function (world) {
  23669. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23670. return _this._tempPickingRay;
  23671. }, predicate, fastCheck);
  23672. };
  23673. /** Launch a ray to try to pick a sprite in the scene
  23674. * @param x position on screen
  23675. * @param y position on screen
  23676. * @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
  23677. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23678. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23679. */
  23680. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23681. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23682. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23683. };
  23684. /** Use the given ray to pick a mesh in the scene
  23685. * @param ray The ray to use to pick meshes
  23686. * @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
  23687. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23688. */
  23689. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23690. var _this = this;
  23691. return this._internalPick(function (world) {
  23692. if (!_this._pickWithRayInverseMatrix) {
  23693. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23694. }
  23695. world.invertToRef(_this._pickWithRayInverseMatrix);
  23696. if (!_this._cachedRayForTransform) {
  23697. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23698. }
  23699. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23700. return _this._cachedRayForTransform;
  23701. }, predicate, fastCheck);
  23702. };
  23703. /**
  23704. * Launch a ray to try to pick a mesh in the scene
  23705. * @param x X position on screen
  23706. * @param y Y position on screen
  23707. * @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
  23708. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23709. */
  23710. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23711. var _this = this;
  23712. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23713. };
  23714. /**
  23715. * Launch a ray to try to pick a mesh in the scene
  23716. * @param ray Ray to use
  23717. * @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
  23718. */
  23719. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23720. var _this = this;
  23721. return this._internalMultiPick(function (world) {
  23722. if (!_this._pickWithRayInverseMatrix) {
  23723. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23724. }
  23725. world.invertToRef(_this._pickWithRayInverseMatrix);
  23726. if (!_this._cachedRayForTransform) {
  23727. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23728. }
  23729. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23730. return _this._cachedRayForTransform;
  23731. }, predicate);
  23732. };
  23733. Scene.prototype.setPointerOverMesh = function (mesh) {
  23734. if (this._pointerOverMesh === mesh) {
  23735. return;
  23736. }
  23737. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23738. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23739. }
  23740. this._pointerOverMesh = mesh;
  23741. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23742. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23743. }
  23744. };
  23745. Scene.prototype.getPointerOverMesh = function () {
  23746. return this._pointerOverMesh;
  23747. };
  23748. Scene.prototype.setPointerOverSprite = function (sprite) {
  23749. if (this._pointerOverSprite === sprite) {
  23750. return;
  23751. }
  23752. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23753. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23754. }
  23755. this._pointerOverSprite = sprite;
  23756. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23757. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23758. }
  23759. };
  23760. Scene.prototype.getPointerOverSprite = function () {
  23761. return this._pointerOverSprite;
  23762. };
  23763. // Physics
  23764. Scene.prototype.getPhysicsEngine = function () {
  23765. return this._physicsEngine;
  23766. };
  23767. /**
  23768. * Enables physics to the current scene
  23769. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23770. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23771. * @return {boolean} was the physics engine initialized
  23772. */
  23773. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23774. if (gravity === void 0) { gravity = null; }
  23775. if (this._physicsEngine) {
  23776. return true;
  23777. }
  23778. try {
  23779. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23780. return true;
  23781. }
  23782. catch (e) {
  23783. BABYLON.Tools.Error(e.message);
  23784. return false;
  23785. }
  23786. };
  23787. Scene.prototype.disablePhysicsEngine = function () {
  23788. if (!this._physicsEngine) {
  23789. return;
  23790. }
  23791. this._physicsEngine.dispose();
  23792. this._physicsEngine = null;
  23793. };
  23794. Scene.prototype.isPhysicsEnabled = function () {
  23795. return this._physicsEngine !== undefined;
  23796. };
  23797. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23798. var mesh = compound.parts[0].mesh;
  23799. if (mesh.physicsImpostor) {
  23800. mesh.physicsImpostor.dispose();
  23801. mesh.physicsImpostor = null;
  23802. }
  23803. };
  23804. // Misc.
  23805. Scene.prototype._rebuildGeometries = function () {
  23806. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23807. var geometry = _a[_i];
  23808. geometry._rebuild();
  23809. }
  23810. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23811. var mesh = _c[_b];
  23812. mesh._rebuild();
  23813. }
  23814. if (this.postProcessManager) {
  23815. this.postProcessManager._rebuild();
  23816. }
  23817. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23818. var layer = _e[_d];
  23819. layer._rebuild();
  23820. }
  23821. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23822. var highlightLayer = _g[_f];
  23823. highlightLayer._rebuild();
  23824. }
  23825. if (this._boundingBoxRenderer) {
  23826. this._boundingBoxRenderer._rebuild();
  23827. }
  23828. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23829. var system = _j[_h];
  23830. system.rebuild();
  23831. }
  23832. if (this._postProcessRenderPipelineManager) {
  23833. this._postProcessRenderPipelineManager._rebuild();
  23834. }
  23835. };
  23836. Scene.prototype._rebuildTextures = function () {
  23837. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23838. var texture = _a[_i];
  23839. texture._rebuild();
  23840. }
  23841. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23842. };
  23843. /**
  23844. * Creates a default light for the scene.
  23845. * @param replace Whether to replace the existing lights in the scene.
  23846. */
  23847. Scene.prototype.createDefaultLight = function (replace) {
  23848. if (replace === void 0) { replace = false; }
  23849. // Dispose existing light in replace mode.
  23850. if (replace) {
  23851. if (this.lights) {
  23852. for (var i = 0; i < this.lights.length; i++) {
  23853. this.lights[i].dispose();
  23854. }
  23855. }
  23856. }
  23857. // Light
  23858. if (this.lights.length === 0) {
  23859. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23860. }
  23861. };
  23862. /**
  23863. * Creates a default camera for the scene.
  23864. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23865. * @param replace Whether to replace the existing active camera in the scene.
  23866. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23867. */
  23868. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23869. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23870. if (replace === void 0) { replace = false; }
  23871. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23872. // Dispose existing camera in replace mode.
  23873. if (replace) {
  23874. if (this.activeCamera) {
  23875. this.activeCamera.dispose();
  23876. this.activeCamera = null;
  23877. }
  23878. }
  23879. // Camera
  23880. if (!this.activeCamera) {
  23881. var worldExtends = this.getWorldExtends();
  23882. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23883. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23884. var camera;
  23885. var radius = worldSize.length() * 1.5;
  23886. if (createArcRotateCamera) {
  23887. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23888. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23889. arcRotateCamera.wheelPrecision = 100 / radius;
  23890. camera = arcRotateCamera;
  23891. }
  23892. else {
  23893. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23894. freeCamera.setTarget(worldCenter);
  23895. camera = freeCamera;
  23896. }
  23897. camera.minZ = radius * 0.01;
  23898. camera.maxZ = radius * 1000;
  23899. camera.speed = radius * 0.2;
  23900. this.activeCamera = camera;
  23901. var canvas = this.getEngine().getRenderingCanvas();
  23902. if (attachCameraControls && canvas) {
  23903. camera.attachControl(canvas);
  23904. }
  23905. }
  23906. };
  23907. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23908. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23909. if (replace === void 0) { replace = false; }
  23910. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23911. this.createDefaultLight(replace);
  23912. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23913. };
  23914. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23915. if (pbr === void 0) { pbr = false; }
  23916. if (scale === void 0) { scale = 1000; }
  23917. if (blur === void 0) { blur = 0; }
  23918. if (environmentTexture) {
  23919. this.environmentTexture = environmentTexture;
  23920. }
  23921. if (!this.environmentTexture) {
  23922. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23923. return null;
  23924. }
  23925. // Skybox
  23926. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23927. if (pbr) {
  23928. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23929. hdrSkyboxMaterial.backFaceCulling = false;
  23930. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23931. if (hdrSkyboxMaterial.reflectionTexture) {
  23932. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23933. }
  23934. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23935. hdrSkyboxMaterial.disableLighting = true;
  23936. hdrSkyboxMaterial.twoSidedLighting = true;
  23937. hdrSkybox.infiniteDistance = true;
  23938. hdrSkybox.material = hdrSkyboxMaterial;
  23939. }
  23940. else {
  23941. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23942. skyboxMaterial.backFaceCulling = false;
  23943. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23944. if (skyboxMaterial.reflectionTexture) {
  23945. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23946. }
  23947. skyboxMaterial.disableLighting = true;
  23948. hdrSkybox.infiniteDistance = true;
  23949. hdrSkybox.material = skyboxMaterial;
  23950. }
  23951. return hdrSkybox;
  23952. };
  23953. Scene.prototype.createDefaultEnvironment = function (options) {
  23954. if (BABYLON.EnvironmentHelper) {
  23955. return new BABYLON.EnvironmentHelper(options, this);
  23956. }
  23957. return null;
  23958. };
  23959. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23960. if (webVROptions === void 0) { webVROptions = {}; }
  23961. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23962. };
  23963. // Tags
  23964. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23965. if (tagsQuery === undefined) {
  23966. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23967. return list;
  23968. }
  23969. var listByTags = [];
  23970. forEach = forEach || (function (item) { return; });
  23971. for (var i in list) {
  23972. var item = list[i];
  23973. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23974. listByTags.push(item);
  23975. forEach(item);
  23976. }
  23977. }
  23978. return listByTags;
  23979. };
  23980. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23981. return this._getByTags(this.meshes, tagsQuery, forEach);
  23982. };
  23983. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23984. return this._getByTags(this.cameras, tagsQuery, forEach);
  23985. };
  23986. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23987. return this._getByTags(this.lights, tagsQuery, forEach);
  23988. };
  23989. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23990. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23991. };
  23992. /**
  23993. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23994. * This allowed control for front to back rendering or reversly depending of the special needs.
  23995. *
  23996. * @param renderingGroupId The rendering group id corresponding to its index
  23997. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23998. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23999. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24000. */
  24001. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24002. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24003. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24004. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24005. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24006. };
  24007. /**
  24008. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24009. *
  24010. * @param renderingGroupId The rendering group id corresponding to its index
  24011. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24012. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24013. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24014. */
  24015. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24016. if (depth === void 0) { depth = true; }
  24017. if (stencil === void 0) { stencil = true; }
  24018. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24019. };
  24020. /**
  24021. * Will flag all materials as dirty to trigger new shader compilation
  24022. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24023. */
  24024. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24025. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24026. var material = _a[_i];
  24027. if (predicate && !predicate(material)) {
  24028. continue;
  24029. }
  24030. material.markAsDirty(flag);
  24031. }
  24032. };
  24033. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24034. var _this = this;
  24035. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24036. this._activeRequests.push(request);
  24037. request.onCompleteObservable.add(function (request) {
  24038. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24039. });
  24040. return request;
  24041. };
  24042. /** @ignore */
  24043. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24044. var _this = this;
  24045. return new Promise(function (resolve, reject) {
  24046. _this._loadFile(url, function (data) {
  24047. resolve(data);
  24048. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24049. reject(exception);
  24050. });
  24051. });
  24052. };
  24053. // Statics
  24054. Scene._FOGMODE_NONE = 0;
  24055. Scene._FOGMODE_EXP = 1;
  24056. Scene._FOGMODE_EXP2 = 2;
  24057. Scene._FOGMODE_LINEAR = 3;
  24058. Scene._uniqueIdCounter = 0;
  24059. Scene.MinDeltaTime = 1.0;
  24060. Scene.MaxDeltaTime = 1000.0;
  24061. /** The distance in pixel that you have to move to prevent some events */
  24062. Scene.DragMovementThreshold = 10; // in pixels
  24063. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24064. Scene.LongPressDelay = 500; // in milliseconds
  24065. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24066. Scene.DoubleClickDelay = 300; // in milliseconds
  24067. /** If you need to check double click without raising a single click at first click, enable this flag */
  24068. Scene.ExclusiveDoubleClickMode = false;
  24069. return Scene;
  24070. }());
  24071. BABYLON.Scene = Scene;
  24072. })(BABYLON || (BABYLON = {}));
  24073. //# sourceMappingURL=babylon.scene.js.map
  24074. var BABYLON;
  24075. (function (BABYLON) {
  24076. /**
  24077. * Set of assets to keep when moving a scene into an asset container.
  24078. */
  24079. var KeepAssets = /** @class */ (function () {
  24080. function KeepAssets() {
  24081. /**
  24082. * Cameras to keep.
  24083. */
  24084. this.cameras = new Array();
  24085. /**
  24086. * Lights to keep.
  24087. */
  24088. this.lights = new Array();
  24089. /**
  24090. * Meshes to keep.
  24091. */
  24092. this.meshes = new Array();
  24093. /**
  24094. * Skeletons to keep.
  24095. */
  24096. this.skeletons = new Array();
  24097. /**
  24098. * ParticleSystems to keep.
  24099. */
  24100. this.particleSystems = new Array();
  24101. /**
  24102. * Animations to keep.
  24103. */
  24104. this.animations = new Array();
  24105. /**
  24106. * MultiMaterials to keep.
  24107. */
  24108. this.multiMaterials = new Array();
  24109. /**
  24110. * Materials to keep.
  24111. */
  24112. this.materials = new Array();
  24113. /**
  24114. * MorphTargetManagers to keep.
  24115. */
  24116. this.morphTargetManagers = new Array();
  24117. /**
  24118. * Geometries to keep.
  24119. */
  24120. this.geometries = new Array();
  24121. /**
  24122. * TransformNodes to keep.
  24123. */
  24124. this.transformNodes = new Array();
  24125. /**
  24126. * LensFlareSystems to keep.
  24127. */
  24128. this.lensFlareSystems = new Array();
  24129. /**
  24130. * ShadowGenerators to keep.
  24131. */
  24132. this.shadowGenerators = new Array();
  24133. /**
  24134. * ActionManagers to keep.
  24135. */
  24136. this.actionManagers = new Array();
  24137. /**
  24138. * Sounds to keep.
  24139. */
  24140. this.sounds = new Array();
  24141. }
  24142. return KeepAssets;
  24143. }());
  24144. BABYLON.KeepAssets = KeepAssets;
  24145. /**
  24146. * Container with a set of assets that can be added or removed from a scene.
  24147. */
  24148. var AssetContainer = /** @class */ (function () {
  24149. /**
  24150. * Instantiates an AssetContainer.
  24151. * @param scene The scene the AssetContainer belongs to.
  24152. */
  24153. function AssetContainer(scene) {
  24154. // Objects
  24155. /**
  24156. * Cameras populated in the container.
  24157. */
  24158. this.cameras = new Array();
  24159. /**
  24160. * Lights populated in the container.
  24161. */
  24162. this.lights = new Array();
  24163. /**
  24164. * Meshes populated in the container.
  24165. */
  24166. this.meshes = new Array();
  24167. /**
  24168. * Skeletons populated in the container.
  24169. */
  24170. this.skeletons = new Array();
  24171. /**
  24172. * ParticleSystems populated in the container.
  24173. */
  24174. this.particleSystems = new Array();
  24175. /**
  24176. * Animations populated in the container.
  24177. */
  24178. this.animations = new Array();
  24179. /**
  24180. * MultiMaterials populated in the container.
  24181. */
  24182. this.multiMaterials = new Array();
  24183. /**
  24184. * Materials populated in the container.
  24185. */
  24186. this.materials = new Array();
  24187. /**
  24188. * MorphTargetManagers populated in the container.
  24189. */
  24190. this.morphTargetManagers = new Array();
  24191. /**
  24192. * Geometries populated in the container.
  24193. */
  24194. this.geometries = new Array();
  24195. /**
  24196. * TransformNodes populated in the container.
  24197. */
  24198. this.transformNodes = new Array();
  24199. /**
  24200. * LensFlareSystems populated in the container.
  24201. */
  24202. this.lensFlareSystems = new Array();
  24203. /**
  24204. * ShadowGenerators populated in the container.
  24205. */
  24206. this.shadowGenerators = new Array();
  24207. /**
  24208. * ActionManagers populated in the container.
  24209. */
  24210. this.actionManagers = new Array();
  24211. /**
  24212. * Sounds populated in the container.
  24213. */
  24214. this.sounds = new Array();
  24215. this.scene = scene;
  24216. }
  24217. /**
  24218. * Adds all the assets from the container to the scene.
  24219. */
  24220. AssetContainer.prototype.addAllToScene = function () {
  24221. var _this = this;
  24222. this.cameras.forEach(function (o) {
  24223. _this.scene.addCamera(o);
  24224. });
  24225. this.lights.forEach(function (o) {
  24226. _this.scene.addLight(o);
  24227. });
  24228. this.meshes.forEach(function (o) {
  24229. _this.scene.addMesh(o);
  24230. });
  24231. this.skeletons.forEach(function (o) {
  24232. _this.scene.addSkeleton(o);
  24233. });
  24234. this.particleSystems.forEach(function (o) {
  24235. _this.scene.addParticleSystem(o);
  24236. });
  24237. this.animations.forEach(function (o) {
  24238. _this.scene.addAnimation(o);
  24239. });
  24240. this.multiMaterials.forEach(function (o) {
  24241. _this.scene.addMultiMaterial(o);
  24242. });
  24243. this.materials.forEach(function (o) {
  24244. _this.scene.addMaterial(o);
  24245. });
  24246. this.morphTargetManagers.forEach(function (o) {
  24247. _this.scene.addMorphTargetManager(o);
  24248. });
  24249. this.geometries.forEach(function (o) {
  24250. _this.scene.addGeometry(o);
  24251. });
  24252. this.transformNodes.forEach(function (o) {
  24253. _this.scene.addTransformNode(o);
  24254. });
  24255. this.lensFlareSystems.forEach(function (o) {
  24256. _this.scene.addLensFlareSystem(o);
  24257. });
  24258. this.actionManagers.forEach(function (o) {
  24259. _this.scene.addActionManager(o);
  24260. });
  24261. this.sounds.forEach(function (o) {
  24262. o.play();
  24263. o.autoplay = true;
  24264. _this.scene.mainSoundTrack.AddSound(o);
  24265. });
  24266. };
  24267. /**
  24268. * Removes all the assets in the container from the scene
  24269. */
  24270. AssetContainer.prototype.removeAllFromScene = function () {
  24271. var _this = this;
  24272. this.cameras.forEach(function (o) {
  24273. _this.scene.removeCamera(o);
  24274. });
  24275. this.lights.forEach(function (o) {
  24276. _this.scene.removeLight(o);
  24277. });
  24278. this.meshes.forEach(function (o) {
  24279. _this.scene.removeMesh(o);
  24280. });
  24281. this.skeletons.forEach(function (o) {
  24282. _this.scene.removeSkeleton(o);
  24283. });
  24284. this.particleSystems.forEach(function (o) {
  24285. _this.scene.removeParticleSystem(o);
  24286. });
  24287. this.animations.forEach(function (o) {
  24288. _this.scene.removeAnimation(o);
  24289. });
  24290. this.multiMaterials.forEach(function (o) {
  24291. _this.scene.removeMultiMaterial(o);
  24292. });
  24293. this.materials.forEach(function (o) {
  24294. _this.scene.removeMaterial(o);
  24295. });
  24296. this.morphTargetManagers.forEach(function (o) {
  24297. _this.scene.removeMorphTargetManager(o);
  24298. });
  24299. this.geometries.forEach(function (o) {
  24300. _this.scene.removeGeometry(o);
  24301. });
  24302. this.transformNodes.forEach(function (o) {
  24303. _this.scene.removeTransformNode(o);
  24304. });
  24305. this.lensFlareSystems.forEach(function (o) {
  24306. _this.scene.removeLensFlareSystem(o);
  24307. });
  24308. this.actionManagers.forEach(function (o) {
  24309. _this.scene.removeActionManager(o);
  24310. });
  24311. this.sounds.forEach(function (o) {
  24312. o.stop();
  24313. o.autoplay = false;
  24314. _this.scene.mainSoundTrack.RemoveSound(o);
  24315. });
  24316. };
  24317. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24318. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24319. var asset = sourceAssets_1[_i];
  24320. var move = true;
  24321. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24322. var keepAsset = keepAssets_1[_a];
  24323. if (asset === keepAsset) {
  24324. move = false;
  24325. break;
  24326. }
  24327. }
  24328. if (move) {
  24329. targetAssets.push(asset);
  24330. }
  24331. }
  24332. };
  24333. /**
  24334. * Removes all the assets contained in the scene and adds them to the container.
  24335. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24336. */
  24337. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24338. if (keepAssets === undefined) {
  24339. keepAssets = new KeepAssets();
  24340. }
  24341. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24342. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24343. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24344. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24345. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24346. Array.prototype.push.apply(this.animations, this.scene.animations);
  24347. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24348. Array.prototype.push.apply(this.lights, this.scene.lights);
  24349. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24350. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24351. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24352. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24353. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24354. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24355. this.removeAllFromScene();
  24356. };
  24357. return AssetContainer;
  24358. }());
  24359. BABYLON.AssetContainer = AssetContainer;
  24360. })(BABYLON || (BABYLON = {}));
  24361. //# sourceMappingURL=babylon.assetContainer.js.map
  24362. var BABYLON;
  24363. (function (BABYLON) {
  24364. var Buffer = /** @class */ (function () {
  24365. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24366. if (instanced === void 0) { instanced = false; }
  24367. if (engine instanceof BABYLON.Mesh) {
  24368. this._engine = engine.getScene().getEngine();
  24369. }
  24370. else {
  24371. this._engine = engine;
  24372. }
  24373. this._updatable = updatable;
  24374. this._data = data;
  24375. this._strideSize = stride;
  24376. if (!postponeInternalCreation) {
  24377. this.create();
  24378. }
  24379. this._instanced = instanced;
  24380. this._instanceDivisor = instanced ? 1 : 0;
  24381. }
  24382. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24383. // a lot of these parameters are ignored as they are overriden by the buffer
  24384. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24385. };
  24386. // Properties
  24387. Buffer.prototype.isUpdatable = function () {
  24388. return this._updatable;
  24389. };
  24390. Buffer.prototype.getData = function () {
  24391. return this._data;
  24392. };
  24393. Buffer.prototype.getBuffer = function () {
  24394. return this._buffer;
  24395. };
  24396. Buffer.prototype.getStrideSize = function () {
  24397. return this._strideSize;
  24398. };
  24399. Buffer.prototype.getIsInstanced = function () {
  24400. return this._instanced;
  24401. };
  24402. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24403. get: function () {
  24404. return this._instanceDivisor;
  24405. },
  24406. set: function (value) {
  24407. this._instanceDivisor = value;
  24408. if (value == 0) {
  24409. this._instanced = false;
  24410. }
  24411. else {
  24412. this._instanced = true;
  24413. }
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. // Methods
  24419. Buffer.prototype.create = function (data) {
  24420. if (data === void 0) { data = null; }
  24421. if (!data && this._buffer) {
  24422. return; // nothing to do
  24423. }
  24424. data = data || this._data;
  24425. if (!data) {
  24426. return;
  24427. }
  24428. if (!this._buffer) {
  24429. if (this._updatable) {
  24430. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24431. this._data = data;
  24432. }
  24433. else {
  24434. this._buffer = this._engine.createVertexBuffer(data);
  24435. }
  24436. }
  24437. else if (this._updatable) {
  24438. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24439. this._data = data;
  24440. }
  24441. };
  24442. Buffer.prototype._rebuild = function () {
  24443. this._buffer = null;
  24444. this.create(this._data);
  24445. };
  24446. Buffer.prototype.update = function (data) {
  24447. this.create(data);
  24448. };
  24449. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24450. if (!this._buffer) {
  24451. return;
  24452. }
  24453. if (this._updatable) {
  24454. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24455. this._data = null;
  24456. }
  24457. };
  24458. Buffer.prototype.dispose = function () {
  24459. if (!this._buffer) {
  24460. return;
  24461. }
  24462. if (this._engine._releaseBuffer(this._buffer)) {
  24463. this._buffer = null;
  24464. }
  24465. };
  24466. return Buffer;
  24467. }());
  24468. BABYLON.Buffer = Buffer;
  24469. })(BABYLON || (BABYLON = {}));
  24470. //# sourceMappingURL=babylon.buffer.js.map
  24471. var BABYLON;
  24472. (function (BABYLON) {
  24473. var VertexBuffer = /** @class */ (function () {
  24474. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24475. if (!stride) {
  24476. // Deduce stride from kind
  24477. switch (kind) {
  24478. case VertexBuffer.PositionKind:
  24479. stride = 3;
  24480. break;
  24481. case VertexBuffer.NormalKind:
  24482. stride = 3;
  24483. break;
  24484. case VertexBuffer.UVKind:
  24485. case VertexBuffer.UV2Kind:
  24486. case VertexBuffer.UV3Kind:
  24487. case VertexBuffer.UV4Kind:
  24488. case VertexBuffer.UV5Kind:
  24489. case VertexBuffer.UV6Kind:
  24490. stride = 2;
  24491. break;
  24492. case VertexBuffer.TangentKind:
  24493. case VertexBuffer.ColorKind:
  24494. stride = 4;
  24495. break;
  24496. case VertexBuffer.MatricesIndicesKind:
  24497. case VertexBuffer.MatricesIndicesExtraKind:
  24498. stride = 4;
  24499. break;
  24500. case VertexBuffer.MatricesWeightsKind:
  24501. case VertexBuffer.MatricesWeightsExtraKind:
  24502. default:
  24503. stride = 4;
  24504. break;
  24505. }
  24506. }
  24507. if (data instanceof BABYLON.Buffer) {
  24508. if (!stride) {
  24509. stride = data.getStrideSize();
  24510. }
  24511. this._buffer = data;
  24512. this._ownsBuffer = false;
  24513. }
  24514. else {
  24515. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24516. this._ownsBuffer = true;
  24517. }
  24518. this._stride = stride;
  24519. this._offset = offset ? offset : 0;
  24520. this._size = size ? size : stride;
  24521. this._kind = kind;
  24522. }
  24523. VertexBuffer.prototype._rebuild = function () {
  24524. if (!this._buffer) {
  24525. return;
  24526. }
  24527. this._buffer._rebuild();
  24528. };
  24529. /**
  24530. * Returns the kind of the VertexBuffer (string).
  24531. */
  24532. VertexBuffer.prototype.getKind = function () {
  24533. return this._kind;
  24534. };
  24535. // Properties
  24536. /**
  24537. * Boolean : is the VertexBuffer updatable ?
  24538. */
  24539. VertexBuffer.prototype.isUpdatable = function () {
  24540. return this._buffer.isUpdatable();
  24541. };
  24542. /**
  24543. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24544. */
  24545. VertexBuffer.prototype.getData = function () {
  24546. return this._buffer.getData();
  24547. };
  24548. /**
  24549. * Returns the WebGLBuffer associated to the VertexBuffer.
  24550. */
  24551. VertexBuffer.prototype.getBuffer = function () {
  24552. return this._buffer.getBuffer();
  24553. };
  24554. /**
  24555. * Returns the stride of the VertexBuffer (integer).
  24556. */
  24557. VertexBuffer.prototype.getStrideSize = function () {
  24558. return this._stride;
  24559. };
  24560. /**
  24561. * Returns the offset (integer).
  24562. */
  24563. VertexBuffer.prototype.getOffset = function () {
  24564. return this._offset;
  24565. };
  24566. /**
  24567. * Returns the VertexBuffer total size (integer).
  24568. */
  24569. VertexBuffer.prototype.getSize = function () {
  24570. return this._size;
  24571. };
  24572. /**
  24573. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24574. */
  24575. VertexBuffer.prototype.getIsInstanced = function () {
  24576. return this._buffer.getIsInstanced();
  24577. };
  24578. /**
  24579. * Returns the instancing divisor, zero for non-instanced (integer).
  24580. */
  24581. VertexBuffer.prototype.getInstanceDivisor = function () {
  24582. return this._buffer.instanceDivisor;
  24583. };
  24584. // Methods
  24585. /**
  24586. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24587. * Returns the created WebGLBuffer.
  24588. */
  24589. VertexBuffer.prototype.create = function (data) {
  24590. return this._buffer.create(data);
  24591. };
  24592. /**
  24593. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24594. * This function will create a new buffer if the current one is not updatable
  24595. * Returns the updated WebGLBuffer.
  24596. */
  24597. VertexBuffer.prototype.update = function (data) {
  24598. return this._buffer.update(data);
  24599. };
  24600. /**
  24601. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24602. * Returns the directly updated WebGLBuffer.
  24603. */
  24604. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24605. return this._buffer.updateDirectly(data, offset);
  24606. };
  24607. /**
  24608. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24609. */
  24610. VertexBuffer.prototype.dispose = function () {
  24611. if (this._ownsBuffer) {
  24612. this._buffer.dispose();
  24613. }
  24614. };
  24615. Object.defineProperty(VertexBuffer, "PositionKind", {
  24616. get: function () {
  24617. return VertexBuffer._PositionKind;
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Object.defineProperty(VertexBuffer, "NormalKind", {
  24623. get: function () {
  24624. return VertexBuffer._NormalKind;
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. Object.defineProperty(VertexBuffer, "TangentKind", {
  24630. get: function () {
  24631. return VertexBuffer._TangentKind;
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(VertexBuffer, "UVKind", {
  24637. get: function () {
  24638. return VertexBuffer._UVKind;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24644. get: function () {
  24645. return VertexBuffer._UV2Kind;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24651. get: function () {
  24652. return VertexBuffer._UV3Kind;
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24658. get: function () {
  24659. return VertexBuffer._UV4Kind;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24665. get: function () {
  24666. return VertexBuffer._UV5Kind;
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24672. get: function () {
  24673. return VertexBuffer._UV6Kind;
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(VertexBuffer, "ColorKind", {
  24679. get: function () {
  24680. return VertexBuffer._ColorKind;
  24681. },
  24682. enumerable: true,
  24683. configurable: true
  24684. });
  24685. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24686. get: function () {
  24687. return VertexBuffer._MatricesIndicesKind;
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24693. get: function () {
  24694. return VertexBuffer._MatricesWeightsKind;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24700. get: function () {
  24701. return VertexBuffer._MatricesIndicesExtraKind;
  24702. },
  24703. enumerable: true,
  24704. configurable: true
  24705. });
  24706. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24707. get: function () {
  24708. return VertexBuffer._MatricesWeightsExtraKind;
  24709. },
  24710. enumerable: true,
  24711. configurable: true
  24712. });
  24713. // Enums
  24714. VertexBuffer._PositionKind = "position";
  24715. VertexBuffer._NormalKind = "normal";
  24716. VertexBuffer._TangentKind = "tangent";
  24717. VertexBuffer._UVKind = "uv";
  24718. VertexBuffer._UV2Kind = "uv2";
  24719. VertexBuffer._UV3Kind = "uv3";
  24720. VertexBuffer._UV4Kind = "uv4";
  24721. VertexBuffer._UV5Kind = "uv5";
  24722. VertexBuffer._UV6Kind = "uv6";
  24723. VertexBuffer._ColorKind = "color";
  24724. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24725. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24726. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24727. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24728. return VertexBuffer;
  24729. }());
  24730. BABYLON.VertexBuffer = VertexBuffer;
  24731. })(BABYLON || (BABYLON = {}));
  24732. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24733. var BABYLON;
  24734. (function (BABYLON) {
  24735. /**
  24736. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24737. */
  24738. var DummyInternalTextureTracker = /** @class */ (function () {
  24739. function DummyInternalTextureTracker() {
  24740. /**
  24741. * Gets or set the previous tracker in the list
  24742. */
  24743. this.previous = null;
  24744. /**
  24745. * Gets or set the next tracker in the list
  24746. */
  24747. this.next = null;
  24748. }
  24749. return DummyInternalTextureTracker;
  24750. }());
  24751. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24752. })(BABYLON || (BABYLON = {}));
  24753. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24754. var BABYLON;
  24755. (function (BABYLON) {
  24756. /**
  24757. * Class used to store data associated with WebGL texture data for the engine
  24758. * This class should not be used directly
  24759. */
  24760. var InternalTexture = /** @class */ (function () {
  24761. /**
  24762. * Creates a new InternalTexture
  24763. * @param engine defines the engine to use
  24764. * @param dataSource defines the type of data that will be used
  24765. */
  24766. function InternalTexture(engine, dataSource) {
  24767. /**
  24768. * Observable called when the texture is loaded
  24769. */
  24770. this.onLoadedObservable = new BABYLON.Observable();
  24771. /**
  24772. * Gets or set the previous tracker in the list
  24773. */
  24774. this.previous = null;
  24775. /**
  24776. * Gets or set the next tracker in the list
  24777. */
  24778. this.next = null;
  24779. // Private
  24780. /** @ignore */
  24781. this._initialSlot = -1;
  24782. /** @ignore */
  24783. this._designatedSlot = -1;
  24784. /** @ignore */
  24785. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24786. /** @ignore */
  24787. this._references = 1;
  24788. this._engine = engine;
  24789. this._dataSource = dataSource;
  24790. this._webGLTexture = engine._createTexture();
  24791. }
  24792. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24793. /**
  24794. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24795. */
  24796. get: function () {
  24797. return this._dataSource;
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. /**
  24803. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24804. */
  24805. InternalTexture.prototype.incrementReferences = function () {
  24806. this._references++;
  24807. };
  24808. /**
  24809. * Change the size of the texture (not the size of the content)
  24810. * @param width defines the new width
  24811. * @param height defines the new height
  24812. * @param depth defines the new depth (1 by default)
  24813. */
  24814. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24815. if (depth === void 0) { depth = 1; }
  24816. this.width = width;
  24817. this.height = height;
  24818. this.depth = depth;
  24819. this.baseWidth = width;
  24820. this.baseHeight = height;
  24821. this.baseDepth = depth;
  24822. this._size = width * height * depth;
  24823. };
  24824. /** @ignore */
  24825. InternalTexture.prototype._rebuild = function () {
  24826. var _this = this;
  24827. var proxy;
  24828. this.isReady = false;
  24829. this._cachedCoordinatesMode = null;
  24830. this._cachedWrapU = null;
  24831. this._cachedWrapV = null;
  24832. this._cachedAnisotropicFilteringLevel = null;
  24833. switch (this._dataSource) {
  24834. case InternalTexture.DATASOURCE_TEMP:
  24835. return;
  24836. case InternalTexture.DATASOURCE_URL:
  24837. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24838. _this.isReady = true;
  24839. }, null, this._buffer, undefined, this.format);
  24840. proxy._swapAndDie(this);
  24841. return;
  24842. case InternalTexture.DATASOURCE_RAW:
  24843. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24844. proxy._swapAndDie(this);
  24845. this.isReady = true;
  24846. return;
  24847. case InternalTexture.DATASOURCE_RAW3D:
  24848. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24849. proxy._swapAndDie(this);
  24850. this.isReady = true;
  24851. return;
  24852. case InternalTexture.DATASOURCE_DYNAMIC:
  24853. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24854. proxy._swapAndDie(this);
  24855. // The engine will make sure to update content so no need to flag it as isReady = true
  24856. return;
  24857. case InternalTexture.DATASOURCE_RENDERTARGET:
  24858. var options = new BABYLON.RenderTargetCreationOptions();
  24859. options.generateDepthBuffer = this._generateDepthBuffer;
  24860. options.generateMipMaps = this.generateMipMaps;
  24861. options.generateStencilBuffer = this._generateStencilBuffer;
  24862. options.samplingMode = this.samplingMode;
  24863. options.type = this.type;
  24864. if (this.isCube) {
  24865. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24866. }
  24867. else {
  24868. var size = {
  24869. width: this.width,
  24870. height: this.height
  24871. };
  24872. proxy = this._engine.createRenderTargetTexture(size, options);
  24873. }
  24874. proxy._swapAndDie(this);
  24875. this.isReady = true;
  24876. return;
  24877. case InternalTexture.DATASOURCE_CUBE:
  24878. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24879. _this.isReady = true;
  24880. }, null, this.format, this._extension);
  24881. proxy._swapAndDie(this);
  24882. return;
  24883. case InternalTexture.DATASOURCE_CUBERAW:
  24884. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24885. proxy._swapAndDie(this);
  24886. this.isReady = true;
  24887. return;
  24888. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24889. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24890. if (proxy) {
  24891. proxy._swapAndDie(_this);
  24892. }
  24893. _this.isReady = true;
  24894. }, null, this.format, this._extension);
  24895. return;
  24896. }
  24897. };
  24898. InternalTexture.prototype._swapAndDie = function (target) {
  24899. target._webGLTexture = this._webGLTexture;
  24900. if (this._framebuffer) {
  24901. target._framebuffer = this._framebuffer;
  24902. }
  24903. if (this._depthStencilBuffer) {
  24904. target._depthStencilBuffer = this._depthStencilBuffer;
  24905. }
  24906. if (this._lodTextureHigh) {
  24907. if (target._lodTextureHigh) {
  24908. target._lodTextureHigh.dispose();
  24909. }
  24910. target._lodTextureHigh = this._lodTextureHigh;
  24911. }
  24912. if (this._lodTextureMid) {
  24913. if (target._lodTextureMid) {
  24914. target._lodTextureMid.dispose();
  24915. }
  24916. target._lodTextureMid = this._lodTextureMid;
  24917. }
  24918. if (this._lodTextureLow) {
  24919. if (target._lodTextureLow) {
  24920. target._lodTextureLow.dispose();
  24921. }
  24922. target._lodTextureLow = this._lodTextureLow;
  24923. }
  24924. var cache = this._engine.getLoadedTexturesCache();
  24925. var index = cache.indexOf(this);
  24926. if (index !== -1) {
  24927. cache.splice(index, 1);
  24928. }
  24929. };
  24930. /**
  24931. * Dispose the current allocated resources
  24932. */
  24933. InternalTexture.prototype.dispose = function () {
  24934. if (!this._webGLTexture) {
  24935. return;
  24936. }
  24937. this._references--;
  24938. if (this._references === 0) {
  24939. this._engine._releaseTexture(this);
  24940. this._webGLTexture = null;
  24941. this.previous = null;
  24942. this.next = null;
  24943. }
  24944. };
  24945. /**
  24946. * The source of the texture data is unknown
  24947. */
  24948. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24949. /**
  24950. * Texture data comes from an URL
  24951. */
  24952. InternalTexture.DATASOURCE_URL = 1;
  24953. /**
  24954. * Texture data is only used for temporary storage
  24955. */
  24956. InternalTexture.DATASOURCE_TEMP = 2;
  24957. /**
  24958. * Texture data comes from raw data (ArrayBuffer)
  24959. */
  24960. InternalTexture.DATASOURCE_RAW = 3;
  24961. /**
  24962. * Texture content is dynamic (video or dynamic texture)
  24963. */
  24964. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24965. /**
  24966. * Texture content is generated by rendering to it
  24967. */
  24968. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24969. /**
  24970. * Texture content is part of a multi render target process
  24971. */
  24972. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24973. /**
  24974. * Texture data comes from a cube data file
  24975. */
  24976. InternalTexture.DATASOURCE_CUBE = 7;
  24977. /**
  24978. * Texture data comes from a raw cube data
  24979. */
  24980. InternalTexture.DATASOURCE_CUBERAW = 8;
  24981. /**
  24982. * Texture data come from a prefiltered cube data file
  24983. */
  24984. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24985. /**
  24986. * Texture content is raw 3D data
  24987. */
  24988. InternalTexture.DATASOURCE_RAW3D = 10;
  24989. return InternalTexture;
  24990. }());
  24991. BABYLON.InternalTexture = InternalTexture;
  24992. })(BABYLON || (BABYLON = {}));
  24993. //# sourceMappingURL=babylon.internalTexture.js.map
  24994. var BABYLON;
  24995. (function (BABYLON) {
  24996. var BaseTexture = /** @class */ (function () {
  24997. function BaseTexture(scene) {
  24998. this._hasAlpha = false;
  24999. this.getAlphaFromRGB = false;
  25000. this.level = 1;
  25001. this.coordinatesIndex = 0;
  25002. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25003. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25004. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25005. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25006. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25007. this.isCube = false;
  25008. this.is3D = false;
  25009. this.gammaSpace = true;
  25010. this.invertZ = false;
  25011. this.lodLevelInAlpha = false;
  25012. this.lodGenerationOffset = 0.0;
  25013. this.lodGenerationScale = 0.8;
  25014. this.isRenderTarget = false;
  25015. this.animations = new Array();
  25016. /**
  25017. * An event triggered when the texture is disposed.
  25018. * @type {BABYLON.Observable}
  25019. */
  25020. this.onDisposeObservable = new BABYLON.Observable();
  25021. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25022. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25023. if (this._scene) {
  25024. this._scene.textures.push(this);
  25025. }
  25026. this._uid = null;
  25027. }
  25028. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25029. get: function () {
  25030. return this._hasAlpha;
  25031. },
  25032. set: function (value) {
  25033. if (this._hasAlpha === value) {
  25034. return;
  25035. }
  25036. this._hasAlpha = value;
  25037. if (this._scene) {
  25038. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25039. }
  25040. },
  25041. enumerable: true,
  25042. configurable: true
  25043. });
  25044. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25045. get: function () {
  25046. return this._coordinatesMode;
  25047. },
  25048. set: function (value) {
  25049. if (this._coordinatesMode === value) {
  25050. return;
  25051. }
  25052. this._coordinatesMode = value;
  25053. if (this._scene) {
  25054. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25055. }
  25056. },
  25057. enumerable: true,
  25058. configurable: true
  25059. });
  25060. Object.defineProperty(BaseTexture.prototype, "uid", {
  25061. get: function () {
  25062. if (!this._uid) {
  25063. this._uid = BABYLON.Tools.RandomId();
  25064. }
  25065. return this._uid;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. BaseTexture.prototype.toString = function () {
  25071. return this.name;
  25072. };
  25073. BaseTexture.prototype.getClassName = function () {
  25074. return "BaseTexture";
  25075. };
  25076. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25077. set: function (callback) {
  25078. if (this._onDisposeObserver) {
  25079. this.onDisposeObservable.remove(this._onDisposeObserver);
  25080. }
  25081. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25082. },
  25083. enumerable: true,
  25084. configurable: true
  25085. });
  25086. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25087. get: function () {
  25088. return true;
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. BaseTexture.prototype.getScene = function () {
  25094. return this._scene;
  25095. };
  25096. BaseTexture.prototype.getTextureMatrix = function () {
  25097. return BABYLON.Matrix.IdentityReadOnly;
  25098. };
  25099. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25100. return BABYLON.Matrix.IdentityReadOnly;
  25101. };
  25102. BaseTexture.prototype.getInternalTexture = function () {
  25103. return this._texture;
  25104. };
  25105. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25106. return !this.isBlocking || this.isReady();
  25107. };
  25108. BaseTexture.prototype.isReady = function () {
  25109. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25110. this.delayLoad();
  25111. return false;
  25112. }
  25113. if (this._texture) {
  25114. return this._texture.isReady;
  25115. }
  25116. return false;
  25117. };
  25118. BaseTexture.prototype.getSize = function () {
  25119. if (this._texture && this._texture.width) {
  25120. return new BABYLON.Size(this._texture.width, this._texture.height);
  25121. }
  25122. if (this._texture && this._texture._size) {
  25123. return new BABYLON.Size(this._texture._size, this._texture._size);
  25124. }
  25125. return BABYLON.Size.Zero();
  25126. };
  25127. BaseTexture.prototype.getBaseSize = function () {
  25128. if (!this.isReady() || !this._texture)
  25129. return BABYLON.Size.Zero();
  25130. if (this._texture._size) {
  25131. return new BABYLON.Size(this._texture._size, this._texture._size);
  25132. }
  25133. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25134. };
  25135. BaseTexture.prototype.scale = function (ratio) {
  25136. };
  25137. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25138. get: function () {
  25139. return false;
  25140. },
  25141. enumerable: true,
  25142. configurable: true
  25143. });
  25144. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25145. if (!this._scene) {
  25146. return null;
  25147. }
  25148. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25149. for (var index = 0; index < texturesCache.length; index++) {
  25150. var texturesCacheEntry = texturesCache[index];
  25151. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25152. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25153. texturesCacheEntry.incrementReferences();
  25154. return texturesCacheEntry;
  25155. }
  25156. }
  25157. }
  25158. return null;
  25159. };
  25160. BaseTexture.prototype._rebuild = function () {
  25161. };
  25162. BaseTexture.prototype.delayLoad = function () {
  25163. };
  25164. BaseTexture.prototype.clone = function () {
  25165. return null;
  25166. };
  25167. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25168. get: function () {
  25169. if (!this._texture) {
  25170. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25171. }
  25172. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25173. },
  25174. enumerable: true,
  25175. configurable: true
  25176. });
  25177. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25178. get: function () {
  25179. if (!this._texture) {
  25180. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25181. }
  25182. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25183. },
  25184. enumerable: true,
  25185. configurable: true
  25186. });
  25187. BaseTexture.prototype.readPixels = function (faceIndex) {
  25188. if (faceIndex === void 0) { faceIndex = 0; }
  25189. if (!this._texture) {
  25190. return null;
  25191. }
  25192. var size = this.getSize();
  25193. var scene = this.getScene();
  25194. if (!scene) {
  25195. return null;
  25196. }
  25197. var engine = scene.getEngine();
  25198. if (this._texture.isCube) {
  25199. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25200. }
  25201. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25202. };
  25203. BaseTexture.prototype.releaseInternalTexture = function () {
  25204. if (this._texture) {
  25205. this._texture.dispose();
  25206. this._texture = null;
  25207. }
  25208. };
  25209. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25210. get: function () {
  25211. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25212. return null;
  25213. }
  25214. if (!this._texture._sphericalPolynomial) {
  25215. this._texture._sphericalPolynomial =
  25216. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25217. }
  25218. return this._texture._sphericalPolynomial;
  25219. },
  25220. set: function (value) {
  25221. if (this._texture) {
  25222. this._texture._sphericalPolynomial = value;
  25223. }
  25224. },
  25225. enumerable: true,
  25226. configurable: true
  25227. });
  25228. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25229. get: function () {
  25230. if (this._texture) {
  25231. return this._texture._lodTextureHigh;
  25232. }
  25233. return null;
  25234. },
  25235. enumerable: true,
  25236. configurable: true
  25237. });
  25238. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25239. get: function () {
  25240. if (this._texture) {
  25241. return this._texture._lodTextureMid;
  25242. }
  25243. return null;
  25244. },
  25245. enumerable: true,
  25246. configurable: true
  25247. });
  25248. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25249. get: function () {
  25250. if (this._texture) {
  25251. return this._texture._lodTextureLow;
  25252. }
  25253. return null;
  25254. },
  25255. enumerable: true,
  25256. configurable: true
  25257. });
  25258. BaseTexture.prototype.dispose = function () {
  25259. if (!this._scene) {
  25260. return;
  25261. }
  25262. // Animations
  25263. this._scene.stopAnimation(this);
  25264. // Remove from scene
  25265. this._scene._removePendingData(this);
  25266. var index = this._scene.textures.indexOf(this);
  25267. if (index >= 0) {
  25268. this._scene.textures.splice(index, 1);
  25269. }
  25270. if (this._texture === undefined) {
  25271. return;
  25272. }
  25273. // Release
  25274. this.releaseInternalTexture();
  25275. // Callback
  25276. this.onDisposeObservable.notifyObservers(this);
  25277. this.onDisposeObservable.clear();
  25278. };
  25279. BaseTexture.prototype.serialize = function () {
  25280. if (!this.name) {
  25281. return null;
  25282. }
  25283. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25284. // Animations
  25285. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25286. return serializationObject;
  25287. };
  25288. BaseTexture.WhenAllReady = function (textures, callback) {
  25289. var numRemaining = textures.length;
  25290. if (numRemaining === 0) {
  25291. callback();
  25292. return;
  25293. }
  25294. var _loop_1 = function () {
  25295. texture = textures[i];
  25296. if (texture.isReady()) {
  25297. if (--numRemaining === 0) {
  25298. callback();
  25299. }
  25300. }
  25301. else {
  25302. onLoadObservable = texture.onLoadObservable;
  25303. var onLoadCallback_1 = function () {
  25304. onLoadObservable.removeCallback(onLoadCallback_1);
  25305. if (--numRemaining === 0) {
  25306. callback();
  25307. }
  25308. };
  25309. onLoadObservable.add(onLoadCallback_1);
  25310. }
  25311. };
  25312. var texture, onLoadObservable;
  25313. for (var i = 0; i < textures.length; i++) {
  25314. _loop_1();
  25315. }
  25316. };
  25317. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25318. __decorate([
  25319. BABYLON.serialize()
  25320. ], BaseTexture.prototype, "name", void 0);
  25321. __decorate([
  25322. BABYLON.serialize("hasAlpha")
  25323. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25324. __decorate([
  25325. BABYLON.serialize()
  25326. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25327. __decorate([
  25328. BABYLON.serialize()
  25329. ], BaseTexture.prototype, "level", void 0);
  25330. __decorate([
  25331. BABYLON.serialize()
  25332. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25333. __decorate([
  25334. BABYLON.serialize("coordinatesMode")
  25335. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25336. __decorate([
  25337. BABYLON.serialize()
  25338. ], BaseTexture.prototype, "wrapU", void 0);
  25339. __decorate([
  25340. BABYLON.serialize()
  25341. ], BaseTexture.prototype, "wrapV", void 0);
  25342. __decorate([
  25343. BABYLON.serialize()
  25344. ], BaseTexture.prototype, "wrapR", void 0);
  25345. __decorate([
  25346. BABYLON.serialize()
  25347. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25348. __decorate([
  25349. BABYLON.serialize()
  25350. ], BaseTexture.prototype, "isCube", void 0);
  25351. __decorate([
  25352. BABYLON.serialize()
  25353. ], BaseTexture.prototype, "is3D", void 0);
  25354. __decorate([
  25355. BABYLON.serialize()
  25356. ], BaseTexture.prototype, "gammaSpace", void 0);
  25357. __decorate([
  25358. BABYLON.serialize()
  25359. ], BaseTexture.prototype, "invertZ", void 0);
  25360. __decorate([
  25361. BABYLON.serialize()
  25362. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25363. __decorate([
  25364. BABYLON.serialize()
  25365. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25366. __decorate([
  25367. BABYLON.serialize()
  25368. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25369. __decorate([
  25370. BABYLON.serialize()
  25371. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25372. return BaseTexture;
  25373. }());
  25374. BABYLON.BaseTexture = BaseTexture;
  25375. })(BABYLON || (BABYLON = {}));
  25376. //# sourceMappingURL=babylon.baseTexture.js.map
  25377. var BABYLON;
  25378. (function (BABYLON) {
  25379. var Texture = /** @class */ (function (_super) {
  25380. __extends(Texture, _super);
  25381. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25382. if (noMipmap === void 0) { noMipmap = false; }
  25383. if (invertY === void 0) { invertY = true; }
  25384. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25385. if (onLoad === void 0) { onLoad = null; }
  25386. if (onError === void 0) { onError = null; }
  25387. if (buffer === void 0) { buffer = null; }
  25388. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25389. var _this = _super.call(this, scene) || this;
  25390. _this.uOffset = 0;
  25391. _this.vOffset = 0;
  25392. _this.uScale = 1.0;
  25393. _this.vScale = 1.0;
  25394. _this.uAng = 0;
  25395. _this.vAng = 0;
  25396. _this.wAng = 0;
  25397. _this._isBlocking = true;
  25398. _this.name = url || "";
  25399. _this.url = url;
  25400. _this._noMipmap = noMipmap;
  25401. _this._invertY = invertY;
  25402. _this._samplingMode = samplingMode;
  25403. _this._buffer = buffer;
  25404. _this._deleteBuffer = deleteBuffer;
  25405. if (format) {
  25406. _this._format = format;
  25407. }
  25408. scene = _this.getScene();
  25409. if (!scene) {
  25410. return _this;
  25411. }
  25412. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25413. var load = function () {
  25414. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25415. _this.onLoadObservable.notifyObservers(_this);
  25416. }
  25417. if (onLoad) {
  25418. onLoad();
  25419. }
  25420. if (!_this.isBlocking && scene) {
  25421. scene.resetCachedMaterial();
  25422. }
  25423. };
  25424. if (!_this.url) {
  25425. _this._delayedOnLoad = load;
  25426. _this._delayedOnError = onError;
  25427. return _this;
  25428. }
  25429. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25430. if (!_this._texture) {
  25431. if (!scene.useDelayedTextureLoading) {
  25432. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25433. if (deleteBuffer) {
  25434. delete _this._buffer;
  25435. }
  25436. }
  25437. else {
  25438. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25439. _this._delayedOnLoad = load;
  25440. _this._delayedOnError = onError;
  25441. }
  25442. }
  25443. else {
  25444. if (_this._texture.isReady) {
  25445. BABYLON.Tools.SetImmediate(function () { return load(); });
  25446. }
  25447. else {
  25448. _this._texture.onLoadedObservable.add(load);
  25449. }
  25450. }
  25451. return _this;
  25452. }
  25453. Object.defineProperty(Texture.prototype, "noMipmap", {
  25454. get: function () {
  25455. return this._noMipmap;
  25456. },
  25457. enumerable: true,
  25458. configurable: true
  25459. });
  25460. Object.defineProperty(Texture.prototype, "isBlocking", {
  25461. get: function () {
  25462. return this._isBlocking;
  25463. },
  25464. set: function (value) {
  25465. this._isBlocking = value;
  25466. },
  25467. enumerable: true,
  25468. configurable: true
  25469. });
  25470. Object.defineProperty(Texture.prototype, "samplingMode", {
  25471. get: function () {
  25472. return this._samplingMode;
  25473. },
  25474. enumerable: true,
  25475. configurable: true
  25476. });
  25477. Texture.prototype.updateURL = function (url) {
  25478. this.url = url;
  25479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25480. this.delayLoad();
  25481. };
  25482. Texture.prototype.delayLoad = function () {
  25483. var _this = this;
  25484. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25485. return;
  25486. }
  25487. var scene = this.getScene();
  25488. if (!scene) {
  25489. return;
  25490. }
  25491. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25492. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25493. if (!this._texture) {
  25494. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25495. if (this._deleteBuffer) {
  25496. delete this._buffer;
  25497. }
  25498. }
  25499. else {
  25500. if (this._texture.isReady) {
  25501. BABYLON.Tools.SetImmediate(function () {
  25502. if (!_this._delayedOnLoad) {
  25503. return;
  25504. }
  25505. _this._delayedOnLoad();
  25506. });
  25507. }
  25508. else {
  25509. if (this._delayedOnLoad) {
  25510. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25511. }
  25512. }
  25513. }
  25514. };
  25515. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25516. if (!this._texture) {
  25517. return;
  25518. }
  25519. var scene = this.getScene();
  25520. if (!scene) {
  25521. return;
  25522. }
  25523. this._samplingMode = samplingMode;
  25524. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25525. };
  25526. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25527. x *= this.uScale;
  25528. y *= this.vScale;
  25529. x -= 0.5 * this.uScale;
  25530. y -= 0.5 * this.vScale;
  25531. z -= 0.5;
  25532. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25533. t.x += 0.5 * this.uScale + this.uOffset;
  25534. t.y += 0.5 * this.vScale + this.vOffset;
  25535. t.z += 0.5;
  25536. };
  25537. Texture.prototype.getTextureMatrix = function () {
  25538. var _this = this;
  25539. if (this.uOffset === this._cachedUOffset &&
  25540. this.vOffset === this._cachedVOffset &&
  25541. this.uScale === this._cachedUScale &&
  25542. this.vScale === this._cachedVScale &&
  25543. this.uAng === this._cachedUAng &&
  25544. this.vAng === this._cachedVAng &&
  25545. this.wAng === this._cachedWAng) {
  25546. return this._cachedTextureMatrix;
  25547. }
  25548. this._cachedUOffset = this.uOffset;
  25549. this._cachedVOffset = this.vOffset;
  25550. this._cachedUScale = this.uScale;
  25551. this._cachedVScale = this.vScale;
  25552. this._cachedUAng = this.uAng;
  25553. this._cachedVAng = this.vAng;
  25554. this._cachedWAng = this.wAng;
  25555. if (!this._cachedTextureMatrix) {
  25556. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25557. this._rowGenerationMatrix = new BABYLON.Matrix();
  25558. this._t0 = BABYLON.Vector3.Zero();
  25559. this._t1 = BABYLON.Vector3.Zero();
  25560. this._t2 = BABYLON.Vector3.Zero();
  25561. }
  25562. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25563. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25564. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25565. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25566. this._t1.subtractInPlace(this._t0);
  25567. this._t2.subtractInPlace(this._t0);
  25568. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25569. this._cachedTextureMatrix.m[0] = this._t1.x;
  25570. this._cachedTextureMatrix.m[1] = this._t1.y;
  25571. this._cachedTextureMatrix.m[2] = this._t1.z;
  25572. this._cachedTextureMatrix.m[4] = this._t2.x;
  25573. this._cachedTextureMatrix.m[5] = this._t2.y;
  25574. this._cachedTextureMatrix.m[6] = this._t2.z;
  25575. this._cachedTextureMatrix.m[8] = this._t0.x;
  25576. this._cachedTextureMatrix.m[9] = this._t0.y;
  25577. this._cachedTextureMatrix.m[10] = this._t0.z;
  25578. var scene = this.getScene();
  25579. if (!scene) {
  25580. return this._cachedTextureMatrix;
  25581. }
  25582. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25583. return mat.hasTexture(_this);
  25584. });
  25585. return this._cachedTextureMatrix;
  25586. };
  25587. Texture.prototype.getReflectionTextureMatrix = function () {
  25588. var _this = this;
  25589. var scene = this.getScene();
  25590. if (!scene) {
  25591. return this._cachedTextureMatrix;
  25592. }
  25593. if (this.uOffset === this._cachedUOffset &&
  25594. this.vOffset === this._cachedVOffset &&
  25595. this.uScale === this._cachedUScale &&
  25596. this.vScale === this._cachedVScale &&
  25597. this.coordinatesMode === this._cachedCoordinatesMode) {
  25598. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25599. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25600. return this._cachedTextureMatrix;
  25601. }
  25602. }
  25603. else {
  25604. return this._cachedTextureMatrix;
  25605. }
  25606. }
  25607. if (!this._cachedTextureMatrix) {
  25608. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25609. }
  25610. if (!this._projectionModeMatrix) {
  25611. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25612. }
  25613. this._cachedUOffset = this.uOffset;
  25614. this._cachedVOffset = this.vOffset;
  25615. this._cachedUScale = this.uScale;
  25616. this._cachedVScale = this.vScale;
  25617. this._cachedCoordinatesMode = this.coordinatesMode;
  25618. switch (this.coordinatesMode) {
  25619. case Texture.PLANAR_MODE:
  25620. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25621. this._cachedTextureMatrix[0] = this.uScale;
  25622. this._cachedTextureMatrix[5] = this.vScale;
  25623. this._cachedTextureMatrix[12] = this.uOffset;
  25624. this._cachedTextureMatrix[13] = this.vOffset;
  25625. break;
  25626. case Texture.PROJECTION_MODE:
  25627. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25628. this._projectionModeMatrix.m[0] = 0.5;
  25629. this._projectionModeMatrix.m[5] = -0.5;
  25630. this._projectionModeMatrix.m[10] = 0.0;
  25631. this._projectionModeMatrix.m[12] = 0.5;
  25632. this._projectionModeMatrix.m[13] = 0.5;
  25633. this._projectionModeMatrix.m[14] = 1.0;
  25634. this._projectionModeMatrix.m[15] = 1.0;
  25635. var projectionMatrix = scene.getProjectionMatrix();
  25636. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25637. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25638. break;
  25639. default:
  25640. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25641. break;
  25642. }
  25643. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25644. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25645. });
  25646. return this._cachedTextureMatrix;
  25647. };
  25648. Texture.prototype.clone = function () {
  25649. var _this = this;
  25650. return BABYLON.SerializationHelper.Clone(function () {
  25651. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25652. }, this);
  25653. };
  25654. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25655. get: function () {
  25656. if (!this._onLoadObservable) {
  25657. this._onLoadObservable = new BABYLON.Observable();
  25658. }
  25659. return this._onLoadObservable;
  25660. },
  25661. enumerable: true,
  25662. configurable: true
  25663. });
  25664. Texture.prototype.serialize = function () {
  25665. var serializationObject = _super.prototype.serialize.call(this);
  25666. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25667. serializationObject.base64String = this._buffer;
  25668. serializationObject.name = serializationObject.name.replace("data:", "");
  25669. }
  25670. return serializationObject;
  25671. };
  25672. Texture.prototype.getClassName = function () {
  25673. return "Texture";
  25674. };
  25675. Texture.prototype.dispose = function () {
  25676. _super.prototype.dispose.call(this);
  25677. if (this.onLoadObservable) {
  25678. this.onLoadObservable.clear();
  25679. this._onLoadObservable = null;
  25680. }
  25681. this._delayedOnLoad = null;
  25682. this._delayedOnError = null;
  25683. };
  25684. // Statics
  25685. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25686. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25687. if (onLoad === void 0) { onLoad = null; }
  25688. if (onError === void 0) { onError = null; }
  25689. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25690. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25691. };
  25692. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25693. if (parsedTexture.customType) {
  25694. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25695. // Update Sampling Mode
  25696. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25697. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25698. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25699. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25700. }
  25701. }
  25702. return parsedCustomTexture;
  25703. }
  25704. if (parsedTexture.isCube) {
  25705. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25706. }
  25707. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25708. return null;
  25709. }
  25710. var texture = BABYLON.SerializationHelper.Parse(function () {
  25711. var generateMipMaps = true;
  25712. if (parsedTexture.noMipmap) {
  25713. generateMipMaps = false;
  25714. }
  25715. if (parsedTexture.mirrorPlane) {
  25716. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25717. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25718. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25719. return mirrorTexture;
  25720. }
  25721. else if (parsedTexture.isRenderTarget) {
  25722. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25723. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25724. return renderTargetTexture;
  25725. }
  25726. else {
  25727. var texture;
  25728. if (parsedTexture.base64String) {
  25729. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25730. }
  25731. else {
  25732. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25733. }
  25734. return texture;
  25735. }
  25736. }, parsedTexture, scene);
  25737. // Update Sampling Mode
  25738. if (parsedTexture.samplingMode) {
  25739. var sampling = parsedTexture.samplingMode;
  25740. if (texture._samplingMode !== sampling) {
  25741. texture.updateSamplingMode(sampling);
  25742. }
  25743. }
  25744. // Animations
  25745. if (parsedTexture.animations) {
  25746. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25747. var parsedAnimation = parsedTexture.animations[animationIndex];
  25748. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25749. }
  25750. }
  25751. return texture;
  25752. };
  25753. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25754. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25755. if (noMipmap === void 0) { noMipmap = false; }
  25756. if (invertY === void 0) { invertY = true; }
  25757. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25758. if (onLoad === void 0) { onLoad = null; }
  25759. if (onError === void 0) { onError = null; }
  25760. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25761. if (name.substr(0, 5) !== "data:") {
  25762. name = "data:" + name;
  25763. }
  25764. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25765. };
  25766. // Constants
  25767. Texture.NEAREST_SAMPLINGMODE = 1;
  25768. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25769. Texture.BILINEAR_SAMPLINGMODE = 2;
  25770. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25771. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25772. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25773. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25774. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25775. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25776. Texture.NEAREST_LINEAR = 7;
  25777. Texture.NEAREST_NEAREST = 8;
  25778. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25779. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25780. Texture.LINEAR_LINEAR = 11;
  25781. Texture.LINEAR_NEAREST = 12;
  25782. Texture.EXPLICIT_MODE = 0;
  25783. Texture.SPHERICAL_MODE = 1;
  25784. Texture.PLANAR_MODE = 2;
  25785. Texture.CUBIC_MODE = 3;
  25786. Texture.PROJECTION_MODE = 4;
  25787. Texture.SKYBOX_MODE = 5;
  25788. Texture.INVCUBIC_MODE = 6;
  25789. Texture.EQUIRECTANGULAR_MODE = 7;
  25790. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25791. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25792. Texture.CLAMP_ADDRESSMODE = 0;
  25793. Texture.WRAP_ADDRESSMODE = 1;
  25794. Texture.MIRROR_ADDRESSMODE = 2;
  25795. __decorate([
  25796. BABYLON.serialize()
  25797. ], Texture.prototype, "url", void 0);
  25798. __decorate([
  25799. BABYLON.serialize()
  25800. ], Texture.prototype, "uOffset", void 0);
  25801. __decorate([
  25802. BABYLON.serialize()
  25803. ], Texture.prototype, "vOffset", void 0);
  25804. __decorate([
  25805. BABYLON.serialize()
  25806. ], Texture.prototype, "uScale", void 0);
  25807. __decorate([
  25808. BABYLON.serialize()
  25809. ], Texture.prototype, "vScale", void 0);
  25810. __decorate([
  25811. BABYLON.serialize()
  25812. ], Texture.prototype, "uAng", void 0);
  25813. __decorate([
  25814. BABYLON.serialize()
  25815. ], Texture.prototype, "vAng", void 0);
  25816. __decorate([
  25817. BABYLON.serialize()
  25818. ], Texture.prototype, "wAng", void 0);
  25819. __decorate([
  25820. BABYLON.serialize()
  25821. ], Texture.prototype, "isBlocking", null);
  25822. return Texture;
  25823. }(BABYLON.BaseTexture));
  25824. BABYLON.Texture = Texture;
  25825. })(BABYLON || (BABYLON = {}));
  25826. //# sourceMappingURL=babylon.texture.js.map
  25827. var BABYLON;
  25828. (function (BABYLON) {
  25829. var _InstancesBatch = /** @class */ (function () {
  25830. function _InstancesBatch() {
  25831. this.mustReturn = false;
  25832. this.visibleInstances = new Array();
  25833. this.renderSelf = new Array();
  25834. }
  25835. return _InstancesBatch;
  25836. }());
  25837. BABYLON._InstancesBatch = _InstancesBatch;
  25838. var Mesh = /** @class */ (function (_super) {
  25839. __extends(Mesh, _super);
  25840. /**
  25841. * @constructor
  25842. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25843. * @param {Scene} scene The scene to add this mesh to.
  25844. * @param {Node} parent The parent of this mesh, if it has one
  25845. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25846. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25847. * When false, achieved by calling a clone(), also passing False.
  25848. * This will make creation of children, recursive.
  25849. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25850. */
  25851. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25852. if (scene === void 0) { scene = null; }
  25853. if (parent === void 0) { parent = null; }
  25854. if (source === void 0) { source = null; }
  25855. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25856. var _this = _super.call(this, name, scene) || this;
  25857. // Events
  25858. /**
  25859. * An event triggered before rendering the mesh
  25860. * @type {BABYLON.Observable}
  25861. */
  25862. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25863. /**
  25864. * An event triggered after rendering the mesh
  25865. * @type {BABYLON.Observable}
  25866. */
  25867. _this.onAfterRenderObservable = new BABYLON.Observable();
  25868. /**
  25869. * An event triggered before drawing the mesh
  25870. * @type {BABYLON.Observable}
  25871. */
  25872. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25873. // Members
  25874. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25875. _this.instances = new Array();
  25876. _this._LODLevels = new Array();
  25877. _this._visibleInstances = {};
  25878. _this._renderIdForInstances = new Array();
  25879. _this._batchCache = new _InstancesBatch();
  25880. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25881. // Use by builder only to know what orientation were the mesh build in.
  25882. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25883. _this.overrideMaterialSideOrientation = null;
  25884. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25885. // Will be used to save a source mesh reference, If any
  25886. _this._source = null;
  25887. scene = _this.getScene();
  25888. if (source) {
  25889. // Source mesh
  25890. _this._source = source;
  25891. // Geometry
  25892. if (source._geometry) {
  25893. source._geometry.applyToMesh(_this);
  25894. }
  25895. // Deep copy
  25896. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25897. // Metadata
  25898. if (source.metadata && source.metadata.clone) {
  25899. _this.metadata = source.metadata.clone();
  25900. }
  25901. else {
  25902. _this.metadata = source.metadata;
  25903. }
  25904. // Tags
  25905. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25906. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25907. }
  25908. // Parent
  25909. _this.parent = source.parent;
  25910. // Pivot
  25911. _this.setPivotMatrix(source.getPivotMatrix());
  25912. _this.id = name + "." + source.id;
  25913. // Material
  25914. _this.material = source.material;
  25915. var index;
  25916. if (!doNotCloneChildren) {
  25917. // Children
  25918. var directDescendants = source.getDescendants(true);
  25919. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25920. var child = directDescendants[index_1];
  25921. if (child.clone) {
  25922. child.clone(name + "." + child.name, _this);
  25923. }
  25924. }
  25925. }
  25926. // Physics clone
  25927. var physicsEngine = _this.getScene().getPhysicsEngine();
  25928. if (clonePhysicsImpostor && physicsEngine) {
  25929. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25930. if (impostor) {
  25931. _this.physicsImpostor = impostor.clone(_this);
  25932. }
  25933. }
  25934. // Particles
  25935. for (index = 0; index < scene.particleSystems.length; index++) {
  25936. var system = scene.particleSystems[index];
  25937. if (system.emitter === source) {
  25938. system.clone(system.name, _this);
  25939. }
  25940. }
  25941. _this.computeWorldMatrix(true);
  25942. }
  25943. // Parent
  25944. if (parent !== null) {
  25945. _this.parent = parent;
  25946. }
  25947. return _this;
  25948. }
  25949. Object.defineProperty(Mesh, "FRONTSIDE", {
  25950. /**
  25951. * Mesh side orientation : usually the external or front surface
  25952. */
  25953. get: function () {
  25954. return Mesh._FRONTSIDE;
  25955. },
  25956. enumerable: true,
  25957. configurable: true
  25958. });
  25959. Object.defineProperty(Mesh, "BACKSIDE", {
  25960. /**
  25961. * Mesh side orientation : usually the internal or back surface
  25962. */
  25963. get: function () {
  25964. return Mesh._BACKSIDE;
  25965. },
  25966. enumerable: true,
  25967. configurable: true
  25968. });
  25969. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25970. /**
  25971. * Mesh side orientation : both internal and external or front and back surfaces
  25972. */
  25973. get: function () {
  25974. return Mesh._DOUBLESIDE;
  25975. },
  25976. enumerable: true,
  25977. configurable: true
  25978. });
  25979. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25980. /**
  25981. * Mesh side orientation : by default, `FRONTSIDE`
  25982. */
  25983. get: function () {
  25984. return Mesh._DEFAULTSIDE;
  25985. },
  25986. enumerable: true,
  25987. configurable: true
  25988. });
  25989. Object.defineProperty(Mesh, "NO_CAP", {
  25990. /**
  25991. * Mesh cap setting : no cap
  25992. */
  25993. get: function () {
  25994. return Mesh._NO_CAP;
  25995. },
  25996. enumerable: true,
  25997. configurable: true
  25998. });
  25999. Object.defineProperty(Mesh, "CAP_START", {
  26000. /**
  26001. * Mesh cap setting : one cap at the beginning of the mesh
  26002. */
  26003. get: function () {
  26004. return Mesh._CAP_START;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. Object.defineProperty(Mesh, "CAP_END", {
  26010. /**
  26011. * Mesh cap setting : one cap at the end of the mesh
  26012. */
  26013. get: function () {
  26014. return Mesh._CAP_END;
  26015. },
  26016. enumerable: true,
  26017. configurable: true
  26018. });
  26019. Object.defineProperty(Mesh, "CAP_ALL", {
  26020. /**
  26021. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26022. */
  26023. get: function () {
  26024. return Mesh._CAP_ALL;
  26025. },
  26026. enumerable: true,
  26027. configurable: true
  26028. });
  26029. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26030. set: function (callback) {
  26031. if (this._onBeforeDrawObserver) {
  26032. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26033. }
  26034. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26040. get: function () {
  26041. return this._morphTargetManager;
  26042. },
  26043. set: function (value) {
  26044. if (this._morphTargetManager === value) {
  26045. return;
  26046. }
  26047. this._morphTargetManager = value;
  26048. this._syncGeometryWithMorphTargetManager();
  26049. },
  26050. enumerable: true,
  26051. configurable: true
  26052. });
  26053. Object.defineProperty(Mesh.prototype, "source", {
  26054. get: function () {
  26055. return this._source;
  26056. },
  26057. enumerable: true,
  26058. configurable: true
  26059. });
  26060. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26061. get: function () {
  26062. return this._unIndexed;
  26063. },
  26064. set: function (value) {
  26065. if (this._unIndexed !== value) {
  26066. this._unIndexed = value;
  26067. this._markSubMeshesAsAttributesDirty();
  26068. }
  26069. },
  26070. enumerable: true,
  26071. configurable: true
  26072. });
  26073. // Methods
  26074. /**
  26075. * Returns the string "Mesh".
  26076. */
  26077. Mesh.prototype.getClassName = function () {
  26078. return "Mesh";
  26079. };
  26080. /**
  26081. * Returns a string.
  26082. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26083. */
  26084. Mesh.prototype.toString = function (fullDetails) {
  26085. var ret = _super.prototype.toString.call(this, fullDetails);
  26086. ret += ", n vertices: " + this.getTotalVertices();
  26087. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26088. if (this.animations) {
  26089. for (var i = 0; i < this.animations.length; i++) {
  26090. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26091. }
  26092. }
  26093. if (fullDetails) {
  26094. if (this._geometry) {
  26095. var ib = this.getIndices();
  26096. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26097. if (vb && ib) {
  26098. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26099. }
  26100. }
  26101. else {
  26102. ret += ", flat shading: UNKNOWN";
  26103. }
  26104. }
  26105. return ret;
  26106. };
  26107. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26108. /**
  26109. * True if the mesh has some Levels Of Details (LOD).
  26110. * Returns a boolean.
  26111. */
  26112. get: function () {
  26113. return this._LODLevels.length > 0;
  26114. },
  26115. enumerable: true,
  26116. configurable: true
  26117. });
  26118. /**
  26119. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26120. * @returns an array of {BABYLON.MeshLODLevel}
  26121. */
  26122. Mesh.prototype.getLODLevels = function () {
  26123. return this._LODLevels;
  26124. };
  26125. Mesh.prototype._sortLODLevels = function () {
  26126. this._LODLevels.sort(function (a, b) {
  26127. if (a.distance < b.distance) {
  26128. return 1;
  26129. }
  26130. if (a.distance > b.distance) {
  26131. return -1;
  26132. }
  26133. return 0;
  26134. });
  26135. };
  26136. /**
  26137. * Add a mesh as LOD level triggered at the given distance.
  26138. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26139. * @param {number} distance The distance from the center of the object to show this level
  26140. * @param {Mesh} mesh The mesh to be added as LOD level
  26141. * @return {Mesh} This mesh (for chaining)
  26142. */
  26143. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26144. if (mesh && mesh._masterMesh) {
  26145. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26146. return this;
  26147. }
  26148. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26149. this._LODLevels.push(level);
  26150. if (mesh) {
  26151. mesh._masterMesh = this;
  26152. }
  26153. this._sortLODLevels();
  26154. return this;
  26155. };
  26156. /**
  26157. * Returns the LOD level mesh at the passed distance or null if not found.
  26158. * It is related to the method `addLODLevel(distance, mesh)`.
  26159. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26160. * Returns an object Mesh or `null`.
  26161. */
  26162. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26163. for (var index = 0; index < this._LODLevels.length; index++) {
  26164. var level = this._LODLevels[index];
  26165. if (level.distance === distance) {
  26166. return level.mesh;
  26167. }
  26168. }
  26169. return null;
  26170. };
  26171. /**
  26172. * Remove a mesh from the LOD array
  26173. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26174. * @param {Mesh} mesh The mesh to be removed.
  26175. * @return {Mesh} This mesh (for chaining)
  26176. */
  26177. Mesh.prototype.removeLODLevel = function (mesh) {
  26178. for (var index = 0; index < this._LODLevels.length; index++) {
  26179. if (this._LODLevels[index].mesh === mesh) {
  26180. this._LODLevels.splice(index, 1);
  26181. if (mesh) {
  26182. mesh._masterMesh = null;
  26183. }
  26184. }
  26185. }
  26186. this._sortLODLevels();
  26187. return this;
  26188. };
  26189. /**
  26190. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26191. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26192. */
  26193. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26194. if (!this._LODLevels || this._LODLevels.length === 0) {
  26195. return this;
  26196. }
  26197. var bSphere;
  26198. if (boundingSphere) {
  26199. bSphere = boundingSphere;
  26200. }
  26201. else {
  26202. var boundingInfo = this.getBoundingInfo();
  26203. bSphere = boundingInfo.boundingSphere;
  26204. }
  26205. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26206. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26207. if (this.onLODLevelSelection) {
  26208. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26209. }
  26210. return this;
  26211. }
  26212. for (var index = 0; index < this._LODLevels.length; index++) {
  26213. var level = this._LODLevels[index];
  26214. if (level.distance < distanceToCamera) {
  26215. if (level.mesh) {
  26216. level.mesh._preActivate();
  26217. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26218. }
  26219. if (this.onLODLevelSelection) {
  26220. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26221. }
  26222. return level.mesh;
  26223. }
  26224. }
  26225. if (this.onLODLevelSelection) {
  26226. this.onLODLevelSelection(distanceToCamera, this, this);
  26227. }
  26228. return this;
  26229. };
  26230. Object.defineProperty(Mesh.prototype, "geometry", {
  26231. /**
  26232. * Returns the mesh internal Geometry object.
  26233. */
  26234. get: function () {
  26235. return this._geometry;
  26236. },
  26237. enumerable: true,
  26238. configurable: true
  26239. });
  26240. /**
  26241. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26242. */
  26243. Mesh.prototype.getTotalVertices = function () {
  26244. if (this._geometry === null || this._geometry === undefined) {
  26245. return 0;
  26246. }
  26247. return this._geometry.getTotalVertices();
  26248. };
  26249. /**
  26250. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26251. * 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.
  26252. * You can force the copy with forceCopy === true
  26253. * Returns null if the mesh has no geometry or no vertex buffer.
  26254. * Possible `kind` values :
  26255. * - BABYLON.VertexBuffer.PositionKind
  26256. * - BABYLON.VertexBuffer.UVKind
  26257. * - BABYLON.VertexBuffer.UV2Kind
  26258. * - BABYLON.VertexBuffer.UV3Kind
  26259. * - BABYLON.VertexBuffer.UV4Kind
  26260. * - BABYLON.VertexBuffer.UV5Kind
  26261. * - BABYLON.VertexBuffer.UV6Kind
  26262. * - BABYLON.VertexBuffer.ColorKind
  26263. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26264. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26265. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26266. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26267. */
  26268. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26269. if (!this._geometry) {
  26270. return null;
  26271. }
  26272. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26273. };
  26274. /**
  26275. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26276. * Returns `null` if the mesh has no geometry.
  26277. * Possible `kind` values :
  26278. * - BABYLON.VertexBuffer.PositionKind
  26279. * - BABYLON.VertexBuffer.UVKind
  26280. * - BABYLON.VertexBuffer.UV2Kind
  26281. * - BABYLON.VertexBuffer.UV3Kind
  26282. * - BABYLON.VertexBuffer.UV4Kind
  26283. * - BABYLON.VertexBuffer.UV5Kind
  26284. * - BABYLON.VertexBuffer.UV6Kind
  26285. * - BABYLON.VertexBuffer.ColorKind
  26286. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26287. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26288. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26289. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26290. */
  26291. Mesh.prototype.getVertexBuffer = function (kind) {
  26292. if (!this._geometry) {
  26293. return null;
  26294. }
  26295. return this._geometry.getVertexBuffer(kind);
  26296. };
  26297. /**
  26298. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26299. * Possible `kind` values :
  26300. * - BABYLON.VertexBuffer.PositionKind
  26301. * - BABYLON.VertexBuffer.UVKind
  26302. * - BABYLON.VertexBuffer.UV2Kind
  26303. * - BABYLON.VertexBuffer.UV3Kind
  26304. * - BABYLON.VertexBuffer.UV4Kind
  26305. * - BABYLON.VertexBuffer.UV5Kind
  26306. * - BABYLON.VertexBuffer.UV6Kind
  26307. * - BABYLON.VertexBuffer.ColorKind
  26308. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26309. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26310. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26311. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26312. */
  26313. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26314. if (!this._geometry) {
  26315. if (this._delayInfo) {
  26316. return this._delayInfo.indexOf(kind) !== -1;
  26317. }
  26318. return false;
  26319. }
  26320. return this._geometry.isVerticesDataPresent(kind);
  26321. };
  26322. /**
  26323. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26324. * Possible `kind` values :
  26325. * - BABYLON.VertexBuffer.PositionKind
  26326. * - BABYLON.VertexBuffer.UVKind
  26327. * - BABYLON.VertexBuffer.UV2Kind
  26328. * - BABYLON.VertexBuffer.UV3Kind
  26329. * - BABYLON.VertexBuffer.UV4Kind
  26330. * - BABYLON.VertexBuffer.UV5Kind
  26331. * - BABYLON.VertexBuffer.UV6Kind
  26332. * - BABYLON.VertexBuffer.ColorKind
  26333. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26334. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26335. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26336. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26337. */
  26338. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26339. if (!this._geometry) {
  26340. if (this._delayInfo) {
  26341. return this._delayInfo.indexOf(kind) !== -1;
  26342. }
  26343. return false;
  26344. }
  26345. return this._geometry.isVertexBufferUpdatable(kind);
  26346. };
  26347. /**
  26348. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26349. * Possible `kind` values :
  26350. * - BABYLON.VertexBuffer.PositionKind
  26351. * - BABYLON.VertexBuffer.UVKind
  26352. * - BABYLON.VertexBuffer.UV2Kind
  26353. * - BABYLON.VertexBuffer.UV3Kind
  26354. * - BABYLON.VertexBuffer.UV4Kind
  26355. * - BABYLON.VertexBuffer.UV5Kind
  26356. * - BABYLON.VertexBuffer.UV6Kind
  26357. * - BABYLON.VertexBuffer.ColorKind
  26358. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26359. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26360. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26361. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26362. */
  26363. Mesh.prototype.getVerticesDataKinds = function () {
  26364. if (!this._geometry) {
  26365. var result = new Array();
  26366. if (this._delayInfo) {
  26367. this._delayInfo.forEach(function (kind, index, array) {
  26368. result.push(kind);
  26369. });
  26370. }
  26371. return result;
  26372. }
  26373. return this._geometry.getVerticesDataKinds();
  26374. };
  26375. /**
  26376. * Returns a positive integer : the total number of indices in this mesh geometry.
  26377. * Returns zero if the mesh has no geometry.
  26378. */
  26379. Mesh.prototype.getTotalIndices = function () {
  26380. if (!this._geometry) {
  26381. return 0;
  26382. }
  26383. return this._geometry.getTotalIndices();
  26384. };
  26385. /**
  26386. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26387. * 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.
  26388. * Returns an empty array if the mesh has no geometry.
  26389. */
  26390. Mesh.prototype.getIndices = function (copyWhenShared) {
  26391. if (!this._geometry) {
  26392. return [];
  26393. }
  26394. return this._geometry.getIndices(copyWhenShared);
  26395. };
  26396. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26397. get: function () {
  26398. return this._masterMesh !== null && this._masterMesh !== undefined;
  26399. },
  26400. enumerable: true,
  26401. configurable: true
  26402. });
  26403. /**
  26404. * Determine if the current mesh is ready to be rendered
  26405. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26406. * @returns true if all associated assets are ready (material, textures, shaders)
  26407. */
  26408. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26409. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26410. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26411. return false;
  26412. }
  26413. if (!_super.prototype.isReady.call(this)) {
  26414. return false;
  26415. }
  26416. if (!this.subMeshes || this.subMeshes.length === 0) {
  26417. return true;
  26418. }
  26419. var engine = this.getEngine();
  26420. var scene = this.getScene();
  26421. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26422. this.computeWorldMatrix();
  26423. var mat = this.material || scene.defaultMaterial;
  26424. if (mat) {
  26425. if (mat.storeEffectOnSubMeshes) {
  26426. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26427. var subMesh = _a[_i];
  26428. var effectiveMaterial = subMesh.getMaterial();
  26429. if (effectiveMaterial) {
  26430. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26431. return false;
  26432. }
  26433. }
  26434. }
  26435. }
  26436. else {
  26437. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26438. return false;
  26439. }
  26440. }
  26441. }
  26442. // Shadows
  26443. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26444. var light = _c[_b];
  26445. var generator = light.getShadowGenerator();
  26446. if (generator) {
  26447. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26448. var subMesh = _e[_d];
  26449. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26450. return false;
  26451. }
  26452. }
  26453. }
  26454. }
  26455. // LOD
  26456. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26457. var lod = _g[_f];
  26458. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26459. return false;
  26460. }
  26461. }
  26462. return true;
  26463. };
  26464. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26465. /**
  26466. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26467. * This property is pertinent only for updatable parametric shapes.
  26468. */
  26469. get: function () {
  26470. return this._areNormalsFrozen;
  26471. },
  26472. enumerable: true,
  26473. configurable: true
  26474. });
  26475. /**
  26476. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26477. * It has no effect at all on other shapes.
  26478. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26479. * Returns the Mesh.
  26480. */
  26481. Mesh.prototype.freezeNormals = function () {
  26482. this._areNormalsFrozen = true;
  26483. return this;
  26484. };
  26485. /**
  26486. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26487. * It has no effect at all on other shapes.
  26488. * It reactivates the mesh normals computation if it was previously frozen.
  26489. * Returns the Mesh.
  26490. */
  26491. Mesh.prototype.unfreezeNormals = function () {
  26492. this._areNormalsFrozen = false;
  26493. return this;
  26494. };
  26495. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26496. /**
  26497. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26498. */
  26499. set: function (count) {
  26500. this._overridenInstanceCount = count;
  26501. },
  26502. enumerable: true,
  26503. configurable: true
  26504. });
  26505. // Methods
  26506. Mesh.prototype._preActivate = function () {
  26507. var sceneRenderId = this.getScene().getRenderId();
  26508. if (this._preActivateId === sceneRenderId) {
  26509. return this;
  26510. }
  26511. this._preActivateId = sceneRenderId;
  26512. this._visibleInstances = null;
  26513. return this;
  26514. };
  26515. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26516. if (this._visibleInstances) {
  26517. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26518. }
  26519. return this;
  26520. };
  26521. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26522. if (!this._visibleInstances) {
  26523. this._visibleInstances = {};
  26524. this._visibleInstances.defaultRenderId = renderId;
  26525. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26526. }
  26527. if (!this._visibleInstances[renderId]) {
  26528. this._visibleInstances[renderId] = new Array();
  26529. }
  26530. this._visibleInstances[renderId].push(instance);
  26531. return this;
  26532. };
  26533. /**
  26534. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26535. * This means the mesh underlying bounding box and sphere are recomputed.
  26536. * Returns the Mesh.
  26537. */
  26538. Mesh.prototype.refreshBoundingInfo = function () {
  26539. return this._refreshBoundingInfo(false);
  26540. };
  26541. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26542. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26543. return this;
  26544. }
  26545. var data = this._getPositionData(applySkeleton);
  26546. if (data) {
  26547. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26548. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26549. }
  26550. if (this.subMeshes) {
  26551. for (var index = 0; index < this.subMeshes.length; index++) {
  26552. this.subMeshes[index].refreshBoundingInfo();
  26553. }
  26554. }
  26555. this._updateBoundingInfo();
  26556. return this;
  26557. };
  26558. Mesh.prototype._getPositionData = function (applySkeleton) {
  26559. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26560. if (data && applySkeleton && this.skeleton) {
  26561. data = BABYLON.Tools.Slice(data);
  26562. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26563. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26564. if (matricesWeightsData && matricesIndicesData) {
  26565. var needExtras = this.numBoneInfluencers > 4;
  26566. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26567. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26568. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26569. var tempVector = BABYLON.Tmp.Vector3[0];
  26570. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26571. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26572. var matWeightIdx = 0;
  26573. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26574. finalMatrix.reset();
  26575. var inf;
  26576. var weight;
  26577. for (inf = 0; inf < 4; inf++) {
  26578. weight = matricesWeightsData[matWeightIdx + inf];
  26579. if (weight <= 0)
  26580. break;
  26581. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26582. finalMatrix.addToSelf(tempMatrix);
  26583. }
  26584. if (needExtras) {
  26585. for (inf = 0; inf < 4; inf++) {
  26586. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26587. if (weight <= 0)
  26588. break;
  26589. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26590. finalMatrix.addToSelf(tempMatrix);
  26591. }
  26592. }
  26593. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26594. tempVector.toArray(data, index);
  26595. }
  26596. }
  26597. }
  26598. return data;
  26599. };
  26600. Mesh.prototype._createGlobalSubMesh = function (force) {
  26601. var totalVertices = this.getTotalVertices();
  26602. if (!totalVertices || !this.getIndices()) {
  26603. return null;
  26604. }
  26605. // Check if we need to recreate the submeshes
  26606. if (this.subMeshes && this.subMeshes.length > 0) {
  26607. var ib = this.getIndices();
  26608. if (!ib) {
  26609. return null;
  26610. }
  26611. var totalIndices = ib.length;
  26612. var needToRecreate = false;
  26613. if (force) {
  26614. needToRecreate = true;
  26615. }
  26616. else {
  26617. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26618. var submesh = _a[_i];
  26619. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26620. needToRecreate = true;
  26621. break;
  26622. }
  26623. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26624. needToRecreate = true;
  26625. break;
  26626. }
  26627. }
  26628. }
  26629. if (!needToRecreate) {
  26630. return this.subMeshes[0];
  26631. }
  26632. }
  26633. this.releaseSubMeshes();
  26634. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26635. };
  26636. Mesh.prototype.subdivide = function (count) {
  26637. if (count < 1) {
  26638. return;
  26639. }
  26640. var totalIndices = this.getTotalIndices();
  26641. var subdivisionSize = (totalIndices / count) | 0;
  26642. var offset = 0;
  26643. // Ensure that subdivisionSize is a multiple of 3
  26644. while (subdivisionSize % 3 !== 0) {
  26645. subdivisionSize++;
  26646. }
  26647. this.releaseSubMeshes();
  26648. for (var index = 0; index < count; index++) {
  26649. if (offset >= totalIndices) {
  26650. break;
  26651. }
  26652. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26653. offset += subdivisionSize;
  26654. }
  26655. this.synchronizeInstances();
  26656. };
  26657. /**
  26658. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26659. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26660. * The `data` are either a numeric array either a Float32Array.
  26661. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26662. * 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).
  26663. * Note that a new underlying VertexBuffer object is created each call.
  26664. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26665. *
  26666. * Possible `kind` values :
  26667. * - BABYLON.VertexBuffer.PositionKind
  26668. * - BABYLON.VertexBuffer.UVKind
  26669. * - BABYLON.VertexBuffer.UV2Kind
  26670. * - BABYLON.VertexBuffer.UV3Kind
  26671. * - BABYLON.VertexBuffer.UV4Kind
  26672. * - BABYLON.VertexBuffer.UV5Kind
  26673. * - BABYLON.VertexBuffer.UV6Kind
  26674. * - BABYLON.VertexBuffer.ColorKind
  26675. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26676. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26677. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26678. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26679. *
  26680. * Returns the Mesh.
  26681. */
  26682. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26683. if (updatable === void 0) { updatable = false; }
  26684. if (!this._geometry) {
  26685. var vertexData = new BABYLON.VertexData();
  26686. vertexData.set(data, kind);
  26687. var scene = this.getScene();
  26688. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26689. }
  26690. else {
  26691. this._geometry.setVerticesData(kind, data, updatable, stride);
  26692. }
  26693. return this;
  26694. };
  26695. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26696. if (updatable === void 0) { updatable = true; }
  26697. var vb = this.getVertexBuffer(kind);
  26698. if (!vb || vb.isUpdatable() === updatable) {
  26699. return;
  26700. }
  26701. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26702. };
  26703. /**
  26704. * Sets the mesh VertexBuffer.
  26705. * Returns the Mesh.
  26706. */
  26707. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26708. if (!this._geometry) {
  26709. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26710. }
  26711. this._geometry.setVerticesBuffer(buffer);
  26712. return this;
  26713. };
  26714. /**
  26715. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26716. * If the mesh has no geometry, it is simply returned as it is.
  26717. * The `data` are either a numeric array either a Float32Array.
  26718. * No new underlying VertexBuffer object is created.
  26719. * 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.
  26720. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26721. *
  26722. * Possible `kind` values :
  26723. * - BABYLON.VertexBuffer.PositionKind
  26724. * - BABYLON.VertexBuffer.UVKind
  26725. * - BABYLON.VertexBuffer.UV2Kind
  26726. * - BABYLON.VertexBuffer.UV3Kind
  26727. * - BABYLON.VertexBuffer.UV4Kind
  26728. * - BABYLON.VertexBuffer.UV5Kind
  26729. * - BABYLON.VertexBuffer.UV6Kind
  26730. * - BABYLON.VertexBuffer.ColorKind
  26731. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26732. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26733. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26734. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26735. *
  26736. * Returns the Mesh.
  26737. */
  26738. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26739. if (!this._geometry) {
  26740. return this;
  26741. }
  26742. if (!makeItUnique) {
  26743. this._geometry.updateVerticesData(kind, data, updateExtends);
  26744. }
  26745. else {
  26746. this.makeGeometryUnique();
  26747. this.updateVerticesData(kind, data, updateExtends, false);
  26748. }
  26749. return this;
  26750. };
  26751. /**
  26752. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26753. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26754. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26755. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26756. * Returns the Mesh.
  26757. */
  26758. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26759. if (computeNormals === void 0) { computeNormals = true; }
  26760. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26761. if (!positions) {
  26762. return this;
  26763. }
  26764. positionFunction(positions);
  26765. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26766. if (computeNormals) {
  26767. var indices = this.getIndices();
  26768. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26769. if (!normals) {
  26770. return this;
  26771. }
  26772. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26773. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26774. }
  26775. return this;
  26776. };
  26777. /**
  26778. * Creates a un-shared specific occurence of the geometry for the mesh.
  26779. * Returns the Mesh.
  26780. */
  26781. Mesh.prototype.makeGeometryUnique = function () {
  26782. if (!this._geometry) {
  26783. return this;
  26784. }
  26785. var oldGeometry = this._geometry;
  26786. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26787. oldGeometry.releaseForMesh(this, true);
  26788. geometry.applyToMesh(this);
  26789. return this;
  26790. };
  26791. /**
  26792. * Sets the mesh indices.
  26793. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26794. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26795. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26796. * This method creates a new index buffer each call.
  26797. * Returns the Mesh.
  26798. */
  26799. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26800. if (totalVertices === void 0) { totalVertices = null; }
  26801. if (updatable === void 0) { updatable = false; }
  26802. if (!this._geometry) {
  26803. var vertexData = new BABYLON.VertexData();
  26804. vertexData.indices = indices;
  26805. var scene = this.getScene();
  26806. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26807. }
  26808. else {
  26809. this._geometry.setIndices(indices, totalVertices, updatable);
  26810. }
  26811. return this;
  26812. };
  26813. /**
  26814. * Update the current index buffer
  26815. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26816. * Returns the Mesh.
  26817. */
  26818. Mesh.prototype.updateIndices = function (indices, offset) {
  26819. if (!this._geometry) {
  26820. return this;
  26821. }
  26822. this._geometry.updateIndices(indices, offset);
  26823. return this;
  26824. };
  26825. /**
  26826. * Invert the geometry to move from a right handed system to a left handed one.
  26827. * Returns the Mesh.
  26828. */
  26829. Mesh.prototype.toLeftHanded = function () {
  26830. if (!this._geometry) {
  26831. return this;
  26832. }
  26833. this._geometry.toLeftHanded();
  26834. return this;
  26835. };
  26836. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26837. if (!this._geometry) {
  26838. return this;
  26839. }
  26840. var engine = this.getScene().getEngine();
  26841. // Wireframe
  26842. var indexToBind;
  26843. if (this._unIndexed) {
  26844. indexToBind = null;
  26845. }
  26846. else {
  26847. switch (fillMode) {
  26848. case BABYLON.Material.PointFillMode:
  26849. indexToBind = null;
  26850. break;
  26851. case BABYLON.Material.WireFrameFillMode:
  26852. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26853. break;
  26854. default:
  26855. case BABYLON.Material.TriangleFillMode:
  26856. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26857. break;
  26858. }
  26859. }
  26860. // VBOs
  26861. this._geometry._bind(effect, indexToBind);
  26862. return this;
  26863. };
  26864. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26865. if (alternate === void 0) { alternate = false; }
  26866. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26867. return this;
  26868. }
  26869. this.onBeforeDrawObservable.notifyObservers(this);
  26870. var scene = this.getScene();
  26871. var engine = scene.getEngine();
  26872. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26873. // or triangles as points
  26874. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26875. }
  26876. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26877. // Triangles as wireframe
  26878. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26879. }
  26880. else {
  26881. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26882. }
  26883. if (scene._isAlternateRenderingEnabled && !alternate) {
  26884. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26885. if (!effect || !scene.activeCamera) {
  26886. return this;
  26887. }
  26888. scene._switchToAlternateCameraConfiguration(true);
  26889. this._effectiveMaterial.bindView(effect);
  26890. this._effectiveMaterial.bindViewProjection(effect);
  26891. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26892. this._draw(subMesh, fillMode, instancesCount, true);
  26893. engine.setViewport(scene.activeCamera.viewport);
  26894. scene._switchToAlternateCameraConfiguration(false);
  26895. this._effectiveMaterial.bindView(effect);
  26896. this._effectiveMaterial.bindViewProjection(effect);
  26897. }
  26898. return this;
  26899. };
  26900. /**
  26901. * Registers for this mesh a javascript function called just before the rendering process.
  26902. * This function is passed the current mesh.
  26903. * Return the Mesh.
  26904. */
  26905. Mesh.prototype.registerBeforeRender = function (func) {
  26906. this.onBeforeRenderObservable.add(func);
  26907. return this;
  26908. };
  26909. /**
  26910. * Disposes a previously registered javascript function called before the rendering.
  26911. * This function is passed the current mesh.
  26912. * Returns the Mesh.
  26913. */
  26914. Mesh.prototype.unregisterBeforeRender = function (func) {
  26915. this.onBeforeRenderObservable.removeCallback(func);
  26916. return this;
  26917. };
  26918. /**
  26919. * Registers for this mesh a javascript function called just after the rendering is complete.
  26920. * This function is passed the current mesh.
  26921. * Returns the Mesh.
  26922. */
  26923. Mesh.prototype.registerAfterRender = function (func) {
  26924. this.onAfterRenderObservable.add(func);
  26925. return this;
  26926. };
  26927. /**
  26928. * Disposes a previously registered javascript function called after the rendering.
  26929. * This function is passed the current mesh.
  26930. * Return the Mesh.
  26931. */
  26932. Mesh.prototype.unregisterAfterRender = function (func) {
  26933. this.onAfterRenderObservable.removeCallback(func);
  26934. return this;
  26935. };
  26936. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26937. var scene = this.getScene();
  26938. this._batchCache.mustReturn = false;
  26939. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26940. this._batchCache.visibleInstances[subMeshId] = null;
  26941. if (this._visibleInstances) {
  26942. var currentRenderId = scene.getRenderId();
  26943. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26944. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26945. var selfRenderId = this._renderId;
  26946. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26947. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26948. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26949. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26950. }
  26951. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26952. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26953. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26954. this._batchCache.mustReturn = true;
  26955. return this._batchCache;
  26956. }
  26957. if (currentRenderId !== selfRenderId) {
  26958. this._batchCache.renderSelf[subMeshId] = false;
  26959. }
  26960. }
  26961. this._renderIdForInstances[subMeshId] = currentRenderId;
  26962. }
  26963. return this._batchCache;
  26964. };
  26965. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26966. var visibleInstances = batch.visibleInstances[subMesh._id];
  26967. if (!visibleInstances) {
  26968. return this;
  26969. }
  26970. var matricesCount = visibleInstances.length + 1;
  26971. var bufferSize = matricesCount * 16 * 4;
  26972. var currentInstancesBufferSize = this._instancesBufferSize;
  26973. var instancesBuffer = this._instancesBuffer;
  26974. while (this._instancesBufferSize < bufferSize) {
  26975. this._instancesBufferSize *= 2;
  26976. }
  26977. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26978. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26979. }
  26980. var offset = 0;
  26981. var instancesCount = 0;
  26982. var world = this.getWorldMatrix();
  26983. if (batch.renderSelf[subMesh._id]) {
  26984. world.copyToArray(this._instancesData, offset);
  26985. offset += 16;
  26986. instancesCount++;
  26987. }
  26988. if (visibleInstances) {
  26989. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26990. var instance = visibleInstances[instanceIndex];
  26991. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26992. offset += 16;
  26993. instancesCount++;
  26994. }
  26995. }
  26996. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26997. if (instancesBuffer) {
  26998. instancesBuffer.dispose();
  26999. }
  27000. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27001. this._instancesBuffer = instancesBuffer;
  27002. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27003. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27004. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27005. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27006. }
  27007. else {
  27008. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27009. }
  27010. this._bind(subMesh, effect, fillMode);
  27011. this._draw(subMesh, fillMode, instancesCount);
  27012. engine.unbindInstanceAttributes();
  27013. return this;
  27014. };
  27015. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27016. var scene = this.getScene();
  27017. var engine = scene.getEngine();
  27018. if (hardwareInstancedRendering) {
  27019. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27020. }
  27021. else {
  27022. if (batch.renderSelf[subMesh._id]) {
  27023. // Draw
  27024. if (onBeforeDraw) {
  27025. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27026. }
  27027. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27028. }
  27029. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27030. if (visibleInstancesForSubMesh) {
  27031. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27032. var instance = visibleInstancesForSubMesh[instanceIndex];
  27033. // World
  27034. var world = instance.getWorldMatrix();
  27035. if (onBeforeDraw) {
  27036. onBeforeDraw(true, world, effectiveMaterial);
  27037. }
  27038. // Draw
  27039. this._draw(subMesh, fillMode);
  27040. }
  27041. }
  27042. }
  27043. return this;
  27044. };
  27045. /**
  27046. * Triggers the draw call for the mesh.
  27047. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27048. * Returns the Mesh.
  27049. */
  27050. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27051. this.checkOcclusionQuery();
  27052. if (this._isOccluded) {
  27053. return this;
  27054. }
  27055. var scene = this.getScene();
  27056. // Managing instances
  27057. var batch = this._getInstancesRenderList(subMesh._id);
  27058. if (batch.mustReturn) {
  27059. return this;
  27060. }
  27061. // Checking geometry state
  27062. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27063. return this;
  27064. }
  27065. this.onBeforeRenderObservable.notifyObservers(this);
  27066. var engine = scene.getEngine();
  27067. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27068. // Material
  27069. var material = subMesh.getMaterial();
  27070. if (!material) {
  27071. return this;
  27072. }
  27073. this._effectiveMaterial = material;
  27074. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27075. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27076. return this;
  27077. }
  27078. }
  27079. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27080. return this;
  27081. }
  27082. // Alpha mode
  27083. if (enableAlphaMode) {
  27084. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27085. }
  27086. // Outline - step 1
  27087. var savedDepthWrite = engine.getDepthWrite();
  27088. if (this.renderOutline) {
  27089. engine.setDepthWrite(false);
  27090. scene.getOutlineRenderer().render(subMesh, batch);
  27091. engine.setDepthWrite(savedDepthWrite);
  27092. }
  27093. var effect;
  27094. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27095. effect = subMesh.effect;
  27096. }
  27097. else {
  27098. effect = this._effectiveMaterial.getEffect();
  27099. }
  27100. if (!effect) {
  27101. return this;
  27102. }
  27103. var sideOrientation = this.overrideMaterialSideOrientation;
  27104. if (sideOrientation == null) {
  27105. sideOrientation = this._effectiveMaterial.sideOrientation;
  27106. if (this._getWorldMatrixDeterminant() < 0) {
  27107. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27108. }
  27109. }
  27110. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27111. if (this._effectiveMaterial.forceDepthWrite) {
  27112. engine.setDepthWrite(true);
  27113. }
  27114. // Bind
  27115. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27116. if (!hardwareInstancedRendering) {
  27117. this._bind(subMesh, effect, fillMode);
  27118. }
  27119. var world = this.getWorldMatrix();
  27120. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27121. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27122. }
  27123. else {
  27124. this._effectiveMaterial.bind(world, this);
  27125. }
  27126. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27127. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27128. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27129. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27130. }
  27131. // Draw
  27132. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27133. // Unbind
  27134. this._effectiveMaterial.unbind();
  27135. // Outline - step 2
  27136. if (this.renderOutline && savedDepthWrite) {
  27137. engine.setDepthWrite(true);
  27138. engine.setColorWrite(false);
  27139. scene.getOutlineRenderer().render(subMesh, batch);
  27140. engine.setColorWrite(true);
  27141. }
  27142. // Overlay
  27143. if (this.renderOverlay) {
  27144. var currentMode = engine.getAlphaMode();
  27145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27146. scene.getOutlineRenderer().render(subMesh, batch, true);
  27147. engine.setAlphaMode(currentMode);
  27148. }
  27149. this.onAfterRenderObservable.notifyObservers(this);
  27150. return this;
  27151. };
  27152. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27153. if (isInstance && effectiveMaterial) {
  27154. effectiveMaterial.bindOnlyWorldMatrix(world);
  27155. }
  27156. };
  27157. /**
  27158. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27159. */
  27160. Mesh.prototype.getEmittedParticleSystems = function () {
  27161. var results = new Array();
  27162. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27163. var particleSystem = this.getScene().particleSystems[index];
  27164. if (particleSystem.emitter === this) {
  27165. results.push(particleSystem);
  27166. }
  27167. }
  27168. return results;
  27169. };
  27170. /**
  27171. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27172. */
  27173. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27174. var results = new Array();
  27175. var descendants = this.getDescendants();
  27176. descendants.push(this);
  27177. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27178. var particleSystem = this.getScene().particleSystems[index];
  27179. var emitter = particleSystem.emitter;
  27180. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27181. results.push(particleSystem);
  27182. }
  27183. }
  27184. return results;
  27185. };
  27186. Mesh.prototype._checkDelayState = function () {
  27187. var scene = this.getScene();
  27188. if (this._geometry) {
  27189. this._geometry.load(scene);
  27190. }
  27191. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27193. this._queueLoad(scene);
  27194. }
  27195. return this;
  27196. };
  27197. Mesh.prototype._queueLoad = function (scene) {
  27198. var _this = this;
  27199. scene._addPendingData(this);
  27200. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27201. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27202. if (data instanceof ArrayBuffer) {
  27203. _this._delayLoadingFunction(data, _this);
  27204. }
  27205. else {
  27206. _this._delayLoadingFunction(JSON.parse(data), _this);
  27207. }
  27208. _this.instances.forEach(function (instance) {
  27209. instance._syncSubMeshes();
  27210. });
  27211. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27212. scene._removePendingData(_this);
  27213. }, function () { }, scene.database, getBinaryData);
  27214. return this;
  27215. };
  27216. /**
  27217. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27218. */
  27219. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27220. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27221. return false;
  27222. }
  27223. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27224. return false;
  27225. }
  27226. this._checkDelayState();
  27227. return true;
  27228. };
  27229. /**
  27230. * Sets the mesh material by the material or multiMaterial `id` property.
  27231. * The material `id` is a string identifying the material or the multiMaterial.
  27232. * This method returns the Mesh.
  27233. */
  27234. Mesh.prototype.setMaterialByID = function (id) {
  27235. var materials = this.getScene().materials;
  27236. var index;
  27237. for (index = materials.length - 1; index > -1; index--) {
  27238. if (materials[index].id === id) {
  27239. this.material = materials[index];
  27240. return this;
  27241. }
  27242. }
  27243. // Multi
  27244. var multiMaterials = this.getScene().multiMaterials;
  27245. for (index = multiMaterials.length - 1; index > -1; index--) {
  27246. if (multiMaterials[index].id === id) {
  27247. this.material = multiMaterials[index];
  27248. return this;
  27249. }
  27250. }
  27251. return this;
  27252. };
  27253. /**
  27254. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27255. */
  27256. Mesh.prototype.getAnimatables = function () {
  27257. var results = new Array();
  27258. if (this.material) {
  27259. results.push(this.material);
  27260. }
  27261. if (this.skeleton) {
  27262. results.push(this.skeleton);
  27263. }
  27264. return results;
  27265. };
  27266. /**
  27267. * Modifies the mesh geometry according to the passed transformation matrix.
  27268. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27269. * The mesh normals are modified accordingly the same transformation.
  27270. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27271. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27272. * Returns the Mesh.
  27273. */
  27274. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27275. // Position
  27276. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27277. return this;
  27278. }
  27279. var submeshes = this.subMeshes.splice(0);
  27280. this._resetPointsArrayCache();
  27281. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27282. var temp = new Array();
  27283. var index;
  27284. for (index = 0; index < data.length; index += 3) {
  27285. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27286. }
  27287. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27288. // Normals
  27289. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27290. return this;
  27291. }
  27292. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27293. temp = [];
  27294. for (index = 0; index < data.length; index += 3) {
  27295. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27296. }
  27297. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27298. // flip faces?
  27299. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27300. this.flipFaces();
  27301. }
  27302. // Restore submeshes
  27303. this.releaseSubMeshes();
  27304. this.subMeshes = submeshes;
  27305. return this;
  27306. };
  27307. /**
  27308. * Modifies the mesh geometry according to its own current World Matrix.
  27309. * The mesh World Matrix is then reset.
  27310. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27311. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27312. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27313. * Returns the Mesh.
  27314. */
  27315. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27316. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27317. this.scaling.copyFromFloats(1, 1, 1);
  27318. this.position.copyFromFloats(0, 0, 0);
  27319. this.rotation.copyFromFloats(0, 0, 0);
  27320. //only if quaternion is already set
  27321. if (this.rotationQuaternion) {
  27322. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27323. }
  27324. this._worldMatrix = BABYLON.Matrix.Identity();
  27325. return this;
  27326. };
  27327. Object.defineProperty(Mesh.prototype, "_positions", {
  27328. // Cache
  27329. get: function () {
  27330. if (this._geometry) {
  27331. return this._geometry._positions;
  27332. }
  27333. return null;
  27334. },
  27335. enumerable: true,
  27336. configurable: true
  27337. });
  27338. Mesh.prototype._resetPointsArrayCache = function () {
  27339. if (this._geometry) {
  27340. this._geometry._resetPointsArrayCache();
  27341. }
  27342. return this;
  27343. };
  27344. Mesh.prototype._generatePointsArray = function () {
  27345. if (this._geometry) {
  27346. return this._geometry._generatePointsArray();
  27347. }
  27348. return false;
  27349. };
  27350. /**
  27351. * Returns a new Mesh object generated from the current mesh properties.
  27352. * This method must not get confused with createInstance().
  27353. * The parameter `name` is a string, the name given to the new mesh.
  27354. * The optional parameter `newParent` can be any Node object (default `null`).
  27355. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27356. * 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.
  27357. */
  27358. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27359. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27360. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27361. };
  27362. /**
  27363. * Disposes the Mesh.
  27364. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27365. * Returns nothing.
  27366. */
  27367. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27368. var _this = this;
  27369. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27370. this.morphTargetManager = null;
  27371. if (this._geometry) {
  27372. this._geometry.releaseForMesh(this, true);
  27373. }
  27374. // Sources
  27375. var meshes = this.getScene().meshes;
  27376. meshes.forEach(function (abstractMesh) {
  27377. var mesh = abstractMesh;
  27378. if (mesh._source && mesh._source === _this) {
  27379. mesh._source = null;
  27380. }
  27381. });
  27382. this._source = null;
  27383. // Instances
  27384. if (this._instancesBuffer) {
  27385. this._instancesBuffer.dispose();
  27386. this._instancesBuffer = null;
  27387. }
  27388. while (this.instances.length) {
  27389. this.instances[0].dispose();
  27390. }
  27391. // Highlight layers.
  27392. var highlightLayers = this.getScene().highlightLayers;
  27393. for (var i = 0; i < highlightLayers.length; i++) {
  27394. var highlightLayer = highlightLayers[i];
  27395. if (highlightLayer) {
  27396. highlightLayer.removeMesh(this);
  27397. highlightLayer.removeExcludedMesh(this);
  27398. }
  27399. }
  27400. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27401. };
  27402. /**
  27403. * Modifies the mesh geometry according to a displacement map.
  27404. * 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.
  27405. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27406. * This method returns nothing.
  27407. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27408. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27409. * 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.
  27410. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27411. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27412. *
  27413. * Returns the Mesh.
  27414. */
  27415. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27416. var _this = this;
  27417. var scene = this.getScene();
  27418. var onload = function (img) {
  27419. // Getting height map data
  27420. var canvas = document.createElement("canvas");
  27421. var context = canvas.getContext("2d");
  27422. var heightMapWidth = img.width;
  27423. var heightMapHeight = img.height;
  27424. canvas.width = heightMapWidth;
  27425. canvas.height = heightMapHeight;
  27426. context.drawImage(img, 0, 0);
  27427. // Create VertexData from map data
  27428. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27429. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27430. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27431. //execute success callback, if set
  27432. if (onSuccess) {
  27433. onSuccess(_this);
  27434. }
  27435. };
  27436. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27437. return this;
  27438. };
  27439. /**
  27440. * Modifies the mesh geometry according to a displacementMap buffer.
  27441. * 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.
  27442. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27443. * This method returns nothing.
  27444. * 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.
  27445. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27446. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27447. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27448. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27449. *
  27450. * Returns the Mesh.
  27451. */
  27452. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27453. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27454. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27455. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27456. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27457. return this;
  27458. }
  27459. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27460. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27461. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27462. var position = BABYLON.Vector3.Zero();
  27463. var normal = BABYLON.Vector3.Zero();
  27464. var uv = BABYLON.Vector2.Zero();
  27465. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27466. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27467. for (var index = 0; index < positions.length; index += 3) {
  27468. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27469. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27470. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27471. // Compute height
  27472. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27473. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27474. var pos = (u + v * heightMapWidth) * 4;
  27475. var r = buffer[pos] / 255.0;
  27476. var g = buffer[pos + 1] / 255.0;
  27477. var b = buffer[pos + 2] / 255.0;
  27478. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27479. normal.normalize();
  27480. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27481. position = position.add(normal);
  27482. position.toArray(positions, index);
  27483. }
  27484. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27485. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27486. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27487. return this;
  27488. };
  27489. /**
  27490. * Modify the mesh to get a flat shading rendering.
  27491. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27492. * This method returns the Mesh.
  27493. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27494. */
  27495. Mesh.prototype.convertToFlatShadedMesh = function () {
  27496. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27497. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27498. var kinds = this.getVerticesDataKinds();
  27499. var vbs = {};
  27500. var data = {};
  27501. var newdata = {};
  27502. var updatableNormals = false;
  27503. var kindIndex;
  27504. var kind;
  27505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27506. kind = kinds[kindIndex];
  27507. var vertexBuffer = this.getVertexBuffer(kind);
  27508. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27509. updatableNormals = vertexBuffer.isUpdatable();
  27510. kinds.splice(kindIndex, 1);
  27511. kindIndex--;
  27512. continue;
  27513. }
  27514. vbs[kind] = vertexBuffer;
  27515. data[kind] = vbs[kind].getData();
  27516. newdata[kind] = [];
  27517. }
  27518. // Save previous submeshes
  27519. var previousSubmeshes = this.subMeshes.slice(0);
  27520. var indices = this.getIndices();
  27521. var totalIndices = this.getTotalIndices();
  27522. // Generating unique vertices per face
  27523. var index;
  27524. for (index = 0; index < totalIndices; index++) {
  27525. var vertexIndex = indices[index];
  27526. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27527. kind = kinds[kindIndex];
  27528. var stride = vbs[kind].getStrideSize();
  27529. for (var offset = 0; offset < stride; offset++) {
  27530. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27531. }
  27532. }
  27533. }
  27534. // Updating faces & normal
  27535. var normals = [];
  27536. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27537. for (index = 0; index < totalIndices; index += 3) {
  27538. indices[index] = index;
  27539. indices[index + 1] = index + 1;
  27540. indices[index + 2] = index + 2;
  27541. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27542. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27543. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27544. var p1p2 = p1.subtract(p2);
  27545. var p3p2 = p3.subtract(p2);
  27546. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27547. // Store same normals for every vertex
  27548. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27549. normals.push(normal.x);
  27550. normals.push(normal.y);
  27551. normals.push(normal.z);
  27552. }
  27553. }
  27554. this.setIndices(indices);
  27555. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27556. // Updating vertex buffers
  27557. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27558. kind = kinds[kindIndex];
  27559. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27560. }
  27561. // Updating submeshes
  27562. this.releaseSubMeshes();
  27563. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27564. var previousOne = previousSubmeshes[submeshIndex];
  27565. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27566. }
  27567. this.synchronizeInstances();
  27568. return this;
  27569. };
  27570. /**
  27571. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27572. * In other words, more vertices, no more indices and a single bigger VBO.
  27573. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27574. * Returns the Mesh.
  27575. */
  27576. Mesh.prototype.convertToUnIndexedMesh = function () {
  27577. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27578. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27579. var kinds = this.getVerticesDataKinds();
  27580. var vbs = {};
  27581. var data = {};
  27582. var newdata = {};
  27583. var kindIndex;
  27584. var kind;
  27585. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27586. kind = kinds[kindIndex];
  27587. var vertexBuffer = this.getVertexBuffer(kind);
  27588. vbs[kind] = vertexBuffer;
  27589. data[kind] = vbs[kind].getData();
  27590. newdata[kind] = [];
  27591. }
  27592. // Save previous submeshes
  27593. var previousSubmeshes = this.subMeshes.slice(0);
  27594. var indices = this.getIndices();
  27595. var totalIndices = this.getTotalIndices();
  27596. // Generating unique vertices per face
  27597. var index;
  27598. for (index = 0; index < totalIndices; index++) {
  27599. var vertexIndex = indices[index];
  27600. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27601. kind = kinds[kindIndex];
  27602. var stride = vbs[kind].getStrideSize();
  27603. for (var offset = 0; offset < stride; offset++) {
  27604. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27605. }
  27606. }
  27607. }
  27608. // Updating indices
  27609. for (index = 0; index < totalIndices; index += 3) {
  27610. indices[index] = index;
  27611. indices[index + 1] = index + 1;
  27612. indices[index + 2] = index + 2;
  27613. }
  27614. this.setIndices(indices);
  27615. // Updating vertex buffers
  27616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27617. kind = kinds[kindIndex];
  27618. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27619. }
  27620. // Updating submeshes
  27621. this.releaseSubMeshes();
  27622. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27623. var previousOne = previousSubmeshes[submeshIndex];
  27624. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27625. }
  27626. this._unIndexed = true;
  27627. this.synchronizeInstances();
  27628. return this;
  27629. };
  27630. /**
  27631. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27632. * This method returns the Mesh.
  27633. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27634. */
  27635. Mesh.prototype.flipFaces = function (flipNormals) {
  27636. if (flipNormals === void 0) { flipNormals = false; }
  27637. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27638. var i;
  27639. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27640. for (i = 0; i < vertex_data.normals.length; i++) {
  27641. vertex_data.normals[i] *= -1;
  27642. }
  27643. }
  27644. if (vertex_data.indices) {
  27645. var temp;
  27646. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27647. // reassign indices
  27648. temp = vertex_data.indices[i + 1];
  27649. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27650. vertex_data.indices[i + 2] = temp;
  27651. }
  27652. }
  27653. vertex_data.applyToMesh(this);
  27654. return this;
  27655. };
  27656. // Instances
  27657. /**
  27658. * Creates a new InstancedMesh object from the mesh model.
  27659. * An instance shares the same properties and the same material than its model.
  27660. * Only these properties of each instance can then be set individually :
  27661. * - position
  27662. * - rotation
  27663. * - rotationQuaternion
  27664. * - setPivotMatrix
  27665. * - scaling
  27666. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27667. * Warning : this method is not supported for Line mesh and LineSystem
  27668. */
  27669. Mesh.prototype.createInstance = function (name) {
  27670. return new BABYLON.InstancedMesh(name, this);
  27671. };
  27672. /**
  27673. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27674. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27675. * This method returns the Mesh.
  27676. */
  27677. Mesh.prototype.synchronizeInstances = function () {
  27678. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27679. var instance = this.instances[instanceIndex];
  27680. instance._syncSubMeshes();
  27681. }
  27682. return this;
  27683. };
  27684. /**
  27685. * Simplify the mesh according to the given array of settings.
  27686. * Function will return immediately and will simplify async. It returns the Mesh.
  27687. * @param settings a collection of simplification settings.
  27688. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27689. * @param type the type of simplification to run.
  27690. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27691. */
  27692. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27693. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27694. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27695. this.getScene().simplificationQueue.addTask({
  27696. settings: settings,
  27697. parallelProcessing: parallelProcessing,
  27698. mesh: this,
  27699. simplificationType: simplificationType,
  27700. successCallback: successCallback
  27701. });
  27702. return this;
  27703. };
  27704. /**
  27705. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27706. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27707. * This should be used together with the simplification to avoid disappearing triangles.
  27708. * Returns the Mesh.
  27709. * @param successCallback an optional success callback to be called after the optimization finished.
  27710. */
  27711. Mesh.prototype.optimizeIndices = function (successCallback) {
  27712. var _this = this;
  27713. var indices = this.getIndices();
  27714. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27715. if (!positions || !indices) {
  27716. return this;
  27717. }
  27718. var vectorPositions = new Array();
  27719. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27720. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27721. }
  27722. var dupes = new Array();
  27723. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27724. var realPos = vectorPositions.length - 1 - iteration;
  27725. var testedPosition = vectorPositions[realPos];
  27726. for (var j = 0; j < realPos; ++j) {
  27727. var againstPosition = vectorPositions[j];
  27728. if (testedPosition.equals(againstPosition)) {
  27729. dupes[realPos] = j;
  27730. break;
  27731. }
  27732. }
  27733. }, function () {
  27734. for (var i = 0; i < indices.length; ++i) {
  27735. indices[i] = dupes[indices[i]] || indices[i];
  27736. }
  27737. //indices are now reordered
  27738. var originalSubMeshes = _this.subMeshes.slice(0);
  27739. _this.setIndices(indices);
  27740. _this.subMeshes = originalSubMeshes;
  27741. if (successCallback) {
  27742. successCallback(_this);
  27743. }
  27744. });
  27745. return this;
  27746. };
  27747. Mesh.prototype.serialize = function (serializationObject) {
  27748. serializationObject.name = this.name;
  27749. serializationObject.id = this.id;
  27750. serializationObject.type = this.getClassName();
  27751. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27752. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27753. }
  27754. serializationObject.position = this.position.asArray();
  27755. if (this.rotationQuaternion) {
  27756. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27757. }
  27758. else if (this.rotation) {
  27759. serializationObject.rotation = this.rotation.asArray();
  27760. }
  27761. serializationObject.scaling = this.scaling.asArray();
  27762. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27763. serializationObject.isEnabled = this.isEnabled(false);
  27764. serializationObject.isVisible = this.isVisible;
  27765. serializationObject.infiniteDistance = this.infiniteDistance;
  27766. serializationObject.pickable = this.isPickable;
  27767. serializationObject.receiveShadows = this.receiveShadows;
  27768. serializationObject.billboardMode = this.billboardMode;
  27769. serializationObject.visibility = this.visibility;
  27770. serializationObject.checkCollisions = this.checkCollisions;
  27771. serializationObject.isBlocker = this.isBlocker;
  27772. // Parent
  27773. if (this.parent) {
  27774. serializationObject.parentId = this.parent.id;
  27775. }
  27776. // Geometry
  27777. serializationObject.isUnIndexed = this.isUnIndexed;
  27778. var geometry = this._geometry;
  27779. if (geometry) {
  27780. var geometryId = geometry.id;
  27781. serializationObject.geometryId = geometryId;
  27782. // SubMeshes
  27783. serializationObject.subMeshes = [];
  27784. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27785. var subMesh = this.subMeshes[subIndex];
  27786. serializationObject.subMeshes.push({
  27787. materialIndex: subMesh.materialIndex,
  27788. verticesStart: subMesh.verticesStart,
  27789. verticesCount: subMesh.verticesCount,
  27790. indexStart: subMesh.indexStart,
  27791. indexCount: subMesh.indexCount
  27792. });
  27793. }
  27794. }
  27795. // Material
  27796. if (this.material) {
  27797. serializationObject.materialId = this.material.id;
  27798. }
  27799. else {
  27800. this.material = null;
  27801. }
  27802. // Morph targets
  27803. if (this.morphTargetManager) {
  27804. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27805. }
  27806. // Skeleton
  27807. if (this.skeleton) {
  27808. serializationObject.skeletonId = this.skeleton.id;
  27809. }
  27810. // Physics
  27811. //TODO implement correct serialization for physics impostors.
  27812. var impostor = this.getPhysicsImpostor();
  27813. if (impostor) {
  27814. serializationObject.physicsMass = impostor.getParam("mass");
  27815. serializationObject.physicsFriction = impostor.getParam("friction");
  27816. serializationObject.physicsRestitution = impostor.getParam("mass");
  27817. serializationObject.physicsImpostor = impostor.type;
  27818. }
  27819. // Metadata
  27820. if (this.metadata) {
  27821. serializationObject.metadata = this.metadata;
  27822. }
  27823. // Instances
  27824. serializationObject.instances = [];
  27825. for (var index = 0; index < this.instances.length; index++) {
  27826. var instance = this.instances[index];
  27827. var serializationInstance = {
  27828. name: instance.name,
  27829. id: instance.id,
  27830. position: instance.position.asArray(),
  27831. scaling: instance.scaling.asArray()
  27832. };
  27833. if (instance.rotationQuaternion) {
  27834. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27835. }
  27836. else if (instance.rotation) {
  27837. serializationInstance.rotation = instance.rotation.asArray();
  27838. }
  27839. serializationObject.instances.push(serializationInstance);
  27840. // Animations
  27841. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27842. serializationInstance.ranges = instance.serializeAnimationRanges();
  27843. }
  27844. //
  27845. // Animations
  27846. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27847. serializationObject.ranges = this.serializeAnimationRanges();
  27848. // Layer mask
  27849. serializationObject.layerMask = this.layerMask;
  27850. // Alpha
  27851. serializationObject.alphaIndex = this.alphaIndex;
  27852. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27853. // Overlay
  27854. serializationObject.overlayAlpha = this.overlayAlpha;
  27855. serializationObject.overlayColor = this.overlayColor.asArray();
  27856. serializationObject.renderOverlay = this.renderOverlay;
  27857. // Fog
  27858. serializationObject.applyFog = this.applyFog;
  27859. // Action Manager
  27860. if (this.actionManager) {
  27861. serializationObject.actions = this.actionManager.serialize(this.name);
  27862. }
  27863. };
  27864. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27865. if (!this.geometry) {
  27866. return;
  27867. }
  27868. this._markSubMeshesAsAttributesDirty();
  27869. var morphTargetManager = this._morphTargetManager;
  27870. if (morphTargetManager && morphTargetManager.vertexCount) {
  27871. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27872. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27873. this.morphTargetManager = null;
  27874. return;
  27875. }
  27876. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27877. var morphTarget = morphTargetManager.getActiveTarget(index);
  27878. var positions = morphTarget.getPositions();
  27879. if (!positions) {
  27880. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27881. return;
  27882. }
  27883. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27884. var normals = morphTarget.getNormals();
  27885. if (normals) {
  27886. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27887. }
  27888. var tangents = morphTarget.getTangents();
  27889. if (tangents) {
  27890. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27891. }
  27892. }
  27893. }
  27894. else {
  27895. var index = 0;
  27896. // Positions
  27897. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27898. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27899. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27900. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27901. }
  27902. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27903. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27904. }
  27905. index++;
  27906. }
  27907. }
  27908. };
  27909. // Statics
  27910. /**
  27911. * Returns a new Mesh object parsed from the source provided.
  27912. * The parameter `parsedMesh` is the source.
  27913. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27914. */
  27915. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27916. var mesh;
  27917. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27918. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27919. }
  27920. else {
  27921. mesh = new Mesh(parsedMesh.name, scene);
  27922. }
  27923. mesh.id = parsedMesh.id;
  27924. if (BABYLON.Tags) {
  27925. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27926. }
  27927. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27928. if (parsedMesh.metadata !== undefined) {
  27929. mesh.metadata = parsedMesh.metadata;
  27930. }
  27931. if (parsedMesh.rotationQuaternion) {
  27932. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27933. }
  27934. else if (parsedMesh.rotation) {
  27935. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27936. }
  27937. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27938. if (parsedMesh.localMatrix) {
  27939. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27940. }
  27941. else if (parsedMesh.pivotMatrix) {
  27942. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27943. }
  27944. mesh.setEnabled(parsedMesh.isEnabled);
  27945. mesh.isVisible = parsedMesh.isVisible;
  27946. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27947. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27948. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27949. if (parsedMesh.applyFog !== undefined) {
  27950. mesh.applyFog = parsedMesh.applyFog;
  27951. }
  27952. if (parsedMesh.pickable !== undefined) {
  27953. mesh.isPickable = parsedMesh.pickable;
  27954. }
  27955. if (parsedMesh.alphaIndex !== undefined) {
  27956. mesh.alphaIndex = parsedMesh.alphaIndex;
  27957. }
  27958. mesh.receiveShadows = parsedMesh.receiveShadows;
  27959. mesh.billboardMode = parsedMesh.billboardMode;
  27960. if (parsedMesh.visibility !== undefined) {
  27961. mesh.visibility = parsedMesh.visibility;
  27962. }
  27963. mesh.checkCollisions = parsedMesh.checkCollisions;
  27964. if (parsedMesh.isBlocker !== undefined) {
  27965. mesh.isBlocker = parsedMesh.isBlocker;
  27966. }
  27967. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27968. // freezeWorldMatrix
  27969. if (parsedMesh.freezeWorldMatrix) {
  27970. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27971. }
  27972. // Parent
  27973. if (parsedMesh.parentId) {
  27974. mesh._waitingParentId = parsedMesh.parentId;
  27975. }
  27976. // Actions
  27977. if (parsedMesh.actions !== undefined) {
  27978. mesh._waitingActions = parsedMesh.actions;
  27979. }
  27980. // Overlay
  27981. if (parsedMesh.overlayAlpha !== undefined) {
  27982. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27983. }
  27984. if (parsedMesh.overlayColor !== undefined) {
  27985. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27986. }
  27987. if (parsedMesh.renderOverlay !== undefined) {
  27988. mesh.renderOverlay = parsedMesh.renderOverlay;
  27989. }
  27990. // Geometry
  27991. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27992. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27993. if (parsedMesh.delayLoadingFile) {
  27994. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27995. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27996. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27997. if (parsedMesh._binaryInfo) {
  27998. mesh._binaryInfo = parsedMesh._binaryInfo;
  27999. }
  28000. mesh._delayInfo = [];
  28001. if (parsedMesh.hasUVs) {
  28002. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28003. }
  28004. if (parsedMesh.hasUVs2) {
  28005. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28006. }
  28007. if (parsedMesh.hasUVs3) {
  28008. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28009. }
  28010. if (parsedMesh.hasUVs4) {
  28011. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28012. }
  28013. if (parsedMesh.hasUVs5) {
  28014. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28015. }
  28016. if (parsedMesh.hasUVs6) {
  28017. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28018. }
  28019. if (parsedMesh.hasColors) {
  28020. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28021. }
  28022. if (parsedMesh.hasMatricesIndices) {
  28023. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28024. }
  28025. if (parsedMesh.hasMatricesWeights) {
  28026. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28027. }
  28028. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28029. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28030. mesh._checkDelayState();
  28031. }
  28032. }
  28033. else {
  28034. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28035. }
  28036. // Material
  28037. if (parsedMesh.materialId) {
  28038. mesh.setMaterialByID(parsedMesh.materialId);
  28039. }
  28040. else {
  28041. mesh.material = null;
  28042. }
  28043. // Morph targets
  28044. if (parsedMesh.morphTargetManagerId > -1) {
  28045. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28046. }
  28047. // Skeleton
  28048. if (parsedMesh.skeletonId > -1) {
  28049. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28050. if (parsedMesh.numBoneInfluencers) {
  28051. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28052. }
  28053. }
  28054. // Animations
  28055. if (parsedMesh.animations) {
  28056. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28057. var parsedAnimation = parsedMesh.animations[animationIndex];
  28058. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28059. }
  28060. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28061. }
  28062. if (parsedMesh.autoAnimate) {
  28063. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28064. }
  28065. // Layer Mask
  28066. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28067. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28068. }
  28069. else {
  28070. mesh.layerMask = 0x0FFFFFFF;
  28071. }
  28072. // Physics
  28073. if (parsedMesh.physicsImpostor) {
  28074. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28075. mass: parsedMesh.physicsMass,
  28076. friction: parsedMesh.physicsFriction,
  28077. restitution: parsedMesh.physicsRestitution
  28078. }, scene);
  28079. }
  28080. // Instances
  28081. if (parsedMesh.instances) {
  28082. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28083. var parsedInstance = parsedMesh.instances[index];
  28084. var instance = mesh.createInstance(parsedInstance.name);
  28085. if (parsedInstance.id) {
  28086. instance.id = parsedInstance.id;
  28087. }
  28088. if (BABYLON.Tags) {
  28089. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28090. }
  28091. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28092. if (parsedInstance.parentId) {
  28093. instance._waitingParentId = parsedInstance.parentId;
  28094. }
  28095. if (parsedInstance.rotationQuaternion) {
  28096. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28097. }
  28098. else if (parsedInstance.rotation) {
  28099. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28100. }
  28101. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28102. instance.checkCollisions = mesh.checkCollisions;
  28103. if (parsedMesh.animations) {
  28104. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28105. parsedAnimation = parsedMesh.animations[animationIndex];
  28106. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28107. }
  28108. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28109. }
  28110. }
  28111. }
  28112. return mesh;
  28113. };
  28114. /**
  28115. * Creates a ribbon mesh.
  28116. * Please consider using the same method from the MeshBuilder class instead.
  28117. * 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.
  28118. *
  28119. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28120. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28121. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28122. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28123. * 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.
  28124. * 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.
  28125. * 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
  28126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28129. */
  28130. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28131. if (closeArray === void 0) { closeArray = false; }
  28132. if (updatable === void 0) { updatable = false; }
  28133. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28134. pathArray: pathArray,
  28135. closeArray: closeArray,
  28136. closePath: closePath,
  28137. offset: offset,
  28138. updatable: updatable,
  28139. sideOrientation: sideOrientation,
  28140. instance: instance
  28141. }, scene);
  28142. };
  28143. /**
  28144. * Creates a plane polygonal mesh. By default, this is a disc.
  28145. * Please consider using the same method from the MeshBuilder class instead.
  28146. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28147. * 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.
  28148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28151. */
  28152. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28153. if (scene === void 0) { scene = null; }
  28154. var options = {
  28155. radius: radius,
  28156. tessellation: tessellation,
  28157. sideOrientation: sideOrientation,
  28158. updatable: updatable
  28159. };
  28160. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28161. };
  28162. /**
  28163. * Creates a box mesh.
  28164. * Please consider using the same method from the MeshBuilder class instead.
  28165. * The parameter `size` sets the size (float) of each box side (default 1).
  28166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28167. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28169. */
  28170. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28171. if (scene === void 0) { scene = null; }
  28172. var options = {
  28173. size: size,
  28174. sideOrientation: sideOrientation,
  28175. updatable: updatable
  28176. };
  28177. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28178. };
  28179. /**
  28180. * Creates a sphere mesh.
  28181. * Please consider using the same method from the MeshBuilder class instead.
  28182. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28183. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28187. */
  28188. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28189. var options = {
  28190. segments: segments,
  28191. diameterX: diameter,
  28192. diameterY: diameter,
  28193. diameterZ: diameter,
  28194. sideOrientation: sideOrientation,
  28195. updatable: updatable
  28196. };
  28197. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28198. };
  28199. /**
  28200. * Creates a cylinder or a cone mesh.
  28201. * Please consider using the same method from the MeshBuilder class instead.
  28202. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28203. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28204. * 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.
  28205. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28206. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28210. */
  28211. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28212. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28213. if (scene !== undefined) {
  28214. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28215. updatable = scene;
  28216. }
  28217. scene = subdivisions;
  28218. subdivisions = 1;
  28219. }
  28220. var options = {
  28221. height: height,
  28222. diameterTop: diameterTop,
  28223. diameterBottom: diameterBottom,
  28224. tessellation: tessellation,
  28225. subdivisions: subdivisions,
  28226. sideOrientation: sideOrientation,
  28227. updatable: updatable
  28228. };
  28229. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28230. };
  28231. // Torus (Code from SharpDX.org)
  28232. /**
  28233. * Creates a torus mesh.
  28234. * Please consider using the same method from the MeshBuilder class instead.
  28235. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28236. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28237. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28241. */
  28242. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28243. var options = {
  28244. diameter: diameter,
  28245. thickness: thickness,
  28246. tessellation: tessellation,
  28247. sideOrientation: sideOrientation,
  28248. updatable: updatable
  28249. };
  28250. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28251. };
  28252. /**
  28253. * Creates a torus knot mesh.
  28254. * Please consider using the same method from the MeshBuilder class instead.
  28255. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28256. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28257. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28258. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28259. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28260. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28262. */
  28263. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28264. var options = {
  28265. radius: radius,
  28266. tube: tube,
  28267. radialSegments: radialSegments,
  28268. tubularSegments: tubularSegments,
  28269. p: p,
  28270. q: q,
  28271. sideOrientation: sideOrientation,
  28272. updatable: updatable
  28273. };
  28274. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28275. };
  28276. /**
  28277. * Creates a line mesh.
  28278. * Please consider using the same method from the MeshBuilder class instead.
  28279. * 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.
  28280. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28281. * The parameter `points` is an array successive Vector3.
  28282. * 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
  28283. * When updating an instance, remember that only point positions can change, not the number of points.
  28284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28285. */
  28286. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28287. if (scene === void 0) { scene = null; }
  28288. if (updatable === void 0) { updatable = false; }
  28289. if (instance === void 0) { instance = null; }
  28290. var options = {
  28291. points: points,
  28292. updatable: updatable,
  28293. instance: instance
  28294. };
  28295. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28296. };
  28297. /**
  28298. * Creates a dashed line mesh.
  28299. * Please consider using the same method from the MeshBuilder class instead.
  28300. * 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.
  28301. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28302. * The parameter `points` is an array successive Vector3.
  28303. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28304. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28305. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28306. * 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
  28307. * When updating an instance, remember that only point positions can change, not the number of points.
  28308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28309. */
  28310. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28311. if (scene === void 0) { scene = null; }
  28312. var options = {
  28313. points: points,
  28314. dashSize: dashSize,
  28315. gapSize: gapSize,
  28316. dashNb: dashNb,
  28317. updatable: updatable,
  28318. instance: instance
  28319. };
  28320. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28321. };
  28322. /**
  28323. * Creates a polygon mesh.
  28324. * Please consider using the same method from the MeshBuilder class instead.
  28325. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28326. * 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.
  28327. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28329. * Remember you can only change the shape positions, not their number when updating a polygon.
  28330. */
  28331. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28332. var options = {
  28333. shape: shape,
  28334. holes: holes,
  28335. updatable: updatable,
  28336. sideOrientation: sideOrientation
  28337. };
  28338. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28339. };
  28340. /**
  28341. * Creates an extruded polygon mesh, with depth in the Y direction.
  28342. * Please consider using the same method from the MeshBuilder class instead.
  28343. */
  28344. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28345. var options = {
  28346. shape: shape,
  28347. holes: holes,
  28348. depth: depth,
  28349. updatable: updatable,
  28350. sideOrientation: sideOrientation
  28351. };
  28352. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28353. };
  28354. /**
  28355. * Creates an extruded shape mesh.
  28356. * 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.
  28357. * Please consider using the same method from the MeshBuilder class instead.
  28358. *
  28359. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28360. * 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
  28361. * extruded along the Z axis.
  28362. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28363. * 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.
  28364. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28365. * 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
  28366. * 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
  28367. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28369. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28371. */
  28372. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28373. if (scene === void 0) { scene = null; }
  28374. var options = {
  28375. shape: shape,
  28376. path: path,
  28377. scale: scale,
  28378. rotation: rotation,
  28379. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28380. sideOrientation: sideOrientation,
  28381. instance: instance,
  28382. updatable: updatable
  28383. };
  28384. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28385. };
  28386. /**
  28387. * Creates an custom extruded shape mesh.
  28388. * 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.
  28389. * Please consider using the same method from the MeshBuilder class instead.
  28390. *
  28391. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28392. * 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
  28393. * extruded along the Z axis.
  28394. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28395. * 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
  28396. * and the distance of this point from the begining of the path :
  28397. * ```javascript
  28398. * var rotationFunction = function(i, distance) {
  28399. * // do things
  28400. * return rotationValue; }
  28401. * ```
  28402. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28403. * 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
  28404. * and the distance of this point from the begining of the path :
  28405. * ```javascript
  28406. * var scaleFunction = function(i, distance) {
  28407. * // do things
  28408. * return scaleValue;}
  28409. * ```
  28410. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28411. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28412. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28413. * 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
  28414. * 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
  28415. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28416. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28417. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28419. */
  28420. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28421. var options = {
  28422. shape: shape,
  28423. path: path,
  28424. scaleFunction: scaleFunction,
  28425. rotationFunction: rotationFunction,
  28426. ribbonCloseArray: ribbonCloseArray,
  28427. ribbonClosePath: ribbonClosePath,
  28428. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28429. sideOrientation: sideOrientation,
  28430. instance: instance,
  28431. updatable: updatable
  28432. };
  28433. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28434. };
  28435. /**
  28436. * Creates lathe mesh.
  28437. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28438. * Please consider using the same method from the MeshBuilder class instead.
  28439. * 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
  28440. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28441. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28442. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28446. */
  28447. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28448. var options = {
  28449. shape: shape,
  28450. radius: radius,
  28451. tessellation: tessellation,
  28452. sideOrientation: sideOrientation,
  28453. updatable: updatable
  28454. };
  28455. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28456. };
  28457. /**
  28458. * Creates a plane mesh.
  28459. * Please consider using the same method from the MeshBuilder class instead.
  28460. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28464. */
  28465. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28466. var options = {
  28467. size: size,
  28468. width: size,
  28469. height: size,
  28470. sideOrientation: sideOrientation,
  28471. updatable: updatable
  28472. };
  28473. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28474. };
  28475. /**
  28476. * Creates a ground mesh.
  28477. * Please consider using the same method from the MeshBuilder class instead.
  28478. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28479. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28481. */
  28482. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28483. var options = {
  28484. width: width,
  28485. height: height,
  28486. subdivisions: subdivisions,
  28487. updatable: updatable
  28488. };
  28489. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28490. };
  28491. /**
  28492. * Creates a tiled ground mesh.
  28493. * Please consider using the same method from the MeshBuilder class instead.
  28494. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28495. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28496. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28497. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28498. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28499. * numbers of subdivisions on the ground width and height of each tile.
  28500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28501. */
  28502. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28503. var options = {
  28504. xmin: xmin,
  28505. zmin: zmin,
  28506. xmax: xmax,
  28507. zmax: zmax,
  28508. subdivisions: subdivisions,
  28509. precision: precision,
  28510. updatable: updatable
  28511. };
  28512. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28513. };
  28514. /**
  28515. * Creates a ground mesh from a height map.
  28516. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28517. * Please consider using the same method from the MeshBuilder class instead.
  28518. * The parameter `url` sets the URL of the height map image resource.
  28519. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28520. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28521. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28522. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28523. * 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).
  28524. * This function is passed the newly built mesh :
  28525. * ```javascript
  28526. * function(mesh) { // do things
  28527. * return; }
  28528. * ```
  28529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28530. */
  28531. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28532. var options = {
  28533. width: width,
  28534. height: height,
  28535. subdivisions: subdivisions,
  28536. minHeight: minHeight,
  28537. maxHeight: maxHeight,
  28538. updatable: updatable,
  28539. onReady: onReady
  28540. };
  28541. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28542. };
  28543. /**
  28544. * Creates a tube mesh.
  28545. * 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.
  28546. * Please consider using the same method from the MeshBuilder class instead.
  28547. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28548. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28549. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28550. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28551. * 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.
  28552. * It must return a radius value (positive float) :
  28553. * ```javascript
  28554. * var radiusFunction = function(i, distance) {
  28555. * // do things
  28556. * return radius; }
  28557. * ```
  28558. * 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
  28559. * 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
  28560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28561. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28563. */
  28564. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28565. var options = {
  28566. path: path,
  28567. radius: radius,
  28568. tessellation: tessellation,
  28569. radiusFunction: radiusFunction,
  28570. arc: 1,
  28571. cap: cap,
  28572. updatable: updatable,
  28573. sideOrientation: sideOrientation,
  28574. instance: instance
  28575. };
  28576. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28577. };
  28578. /**
  28579. * Creates a polyhedron mesh.
  28580. * Please consider using the same method from the MeshBuilder class instead.
  28581. * 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
  28582. * to choose the wanted type.
  28583. * The parameter `size` (positive float, default 1) sets the polygon size.
  28584. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28585. * 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`.
  28586. * 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
  28587. * 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)`).
  28588. * 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
  28589. * 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.
  28590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28593. */
  28594. Mesh.CreatePolyhedron = function (name, options, scene) {
  28595. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28596. };
  28597. /**
  28598. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28599. * Please consider using the same method from the MeshBuilder class instead.
  28600. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28601. * 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`).
  28602. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28603. * 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.
  28604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28605. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28607. */
  28608. Mesh.CreateIcoSphere = function (name, options, scene) {
  28609. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28610. };
  28611. /**
  28612. * Creates a decal mesh.
  28613. * Please consider using the same method from the MeshBuilder class instead.
  28614. * 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.
  28615. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28616. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28617. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28618. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28619. */
  28620. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28621. var options = {
  28622. position: position,
  28623. normal: normal,
  28624. size: size,
  28625. angle: angle
  28626. };
  28627. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28628. };
  28629. // Skeletons
  28630. /**
  28631. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28632. */
  28633. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28634. if (!this._sourcePositions) {
  28635. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28636. if (!source) {
  28637. return this._sourcePositions;
  28638. }
  28639. this._sourcePositions = new Float32Array(source);
  28640. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28641. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28642. }
  28643. }
  28644. return this._sourcePositions;
  28645. };
  28646. /**
  28647. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28648. */
  28649. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28650. if (!this._sourceNormals) {
  28651. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28652. if (!source) {
  28653. return this._sourceNormals;
  28654. }
  28655. this._sourceNormals = new Float32Array(source);
  28656. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28657. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28658. }
  28659. }
  28660. return this._sourceNormals;
  28661. };
  28662. /**
  28663. * Updates the vertex buffer by applying transformation from the bones.
  28664. * Returns the Mesh.
  28665. *
  28666. * @param {skeleton} skeleton to apply
  28667. */
  28668. Mesh.prototype.applySkeleton = function (skeleton) {
  28669. if (!this.geometry) {
  28670. return this;
  28671. }
  28672. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28673. return this;
  28674. }
  28675. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28676. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28677. return this;
  28678. }
  28679. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28680. return this;
  28681. }
  28682. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28683. return this;
  28684. }
  28685. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28686. return this;
  28687. }
  28688. if (!this._sourcePositions) {
  28689. var submeshes = this.subMeshes.slice();
  28690. this.setPositionsForCPUSkinning();
  28691. this.subMeshes = submeshes;
  28692. }
  28693. if (!this._sourceNormals) {
  28694. this.setNormalsForCPUSkinning();
  28695. }
  28696. // positionsData checks for not being Float32Array will only pass at most once
  28697. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28698. if (!positionsData) {
  28699. return this;
  28700. }
  28701. if (!(positionsData instanceof Float32Array)) {
  28702. positionsData = new Float32Array(positionsData);
  28703. }
  28704. // normalsData checks for not being Float32Array will only pass at most once
  28705. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28706. if (!normalsData) {
  28707. return this;
  28708. }
  28709. if (!(normalsData instanceof Float32Array)) {
  28710. normalsData = new Float32Array(normalsData);
  28711. }
  28712. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28713. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28714. if (!matricesWeightsData || !matricesIndicesData) {
  28715. return this;
  28716. }
  28717. var needExtras = this.numBoneInfluencers > 4;
  28718. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28719. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28720. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28721. var tempVector3 = BABYLON.Vector3.Zero();
  28722. var finalMatrix = new BABYLON.Matrix();
  28723. var tempMatrix = new BABYLON.Matrix();
  28724. var matWeightIdx = 0;
  28725. var inf;
  28726. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28727. var weight;
  28728. for (inf = 0; inf < 4; inf++) {
  28729. weight = matricesWeightsData[matWeightIdx + inf];
  28730. if (weight > 0) {
  28731. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28732. finalMatrix.addToSelf(tempMatrix);
  28733. }
  28734. else
  28735. break;
  28736. }
  28737. if (needExtras) {
  28738. for (inf = 0; inf < 4; inf++) {
  28739. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28740. if (weight > 0) {
  28741. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28742. finalMatrix.addToSelf(tempMatrix);
  28743. }
  28744. else
  28745. break;
  28746. }
  28747. }
  28748. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28749. tempVector3.toArray(positionsData, index);
  28750. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28751. tempVector3.toArray(normalsData, index);
  28752. finalMatrix.reset();
  28753. }
  28754. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28755. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28756. return this;
  28757. };
  28758. // Tools
  28759. /**
  28760. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28761. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28762. */
  28763. Mesh.MinMax = function (meshes) {
  28764. var minVector = null;
  28765. var maxVector = null;
  28766. meshes.forEach(function (mesh, index, array) {
  28767. var boundingInfo = mesh.getBoundingInfo();
  28768. var boundingBox = boundingInfo.boundingBox;
  28769. if (!minVector || !maxVector) {
  28770. minVector = boundingBox.minimumWorld;
  28771. maxVector = boundingBox.maximumWorld;
  28772. }
  28773. else {
  28774. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28775. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28776. }
  28777. });
  28778. if (!minVector || !maxVector) {
  28779. return {
  28780. min: BABYLON.Vector3.Zero(),
  28781. max: BABYLON.Vector3.Zero()
  28782. };
  28783. }
  28784. return {
  28785. min: minVector,
  28786. max: maxVector
  28787. };
  28788. };
  28789. /**
  28790. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28791. */
  28792. Mesh.Center = function (meshesOrMinMaxVector) {
  28793. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28794. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28795. };
  28796. /**
  28797. * Merge the array of meshes into a single mesh for performance reasons.
  28798. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28799. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28800. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28801. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28802. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28803. */
  28804. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28805. if (disposeSource === void 0) { disposeSource = true; }
  28806. var index;
  28807. if (!allow32BitsIndices) {
  28808. var totalVertices = 0;
  28809. // Counting vertices
  28810. for (index = 0; index < meshes.length; index++) {
  28811. if (meshes[index]) {
  28812. totalVertices += meshes[index].getTotalVertices();
  28813. if (totalVertices > 65536) {
  28814. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28815. return null;
  28816. }
  28817. }
  28818. }
  28819. }
  28820. // Merge
  28821. var vertexData = null;
  28822. var otherVertexData;
  28823. var indiceArray = new Array();
  28824. var source = null;
  28825. for (index = 0; index < meshes.length; index++) {
  28826. if (meshes[index]) {
  28827. meshes[index].computeWorldMatrix(true);
  28828. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28829. otherVertexData.transform(meshes[index].getWorldMatrix());
  28830. if (vertexData) {
  28831. vertexData.merge(otherVertexData);
  28832. }
  28833. else {
  28834. vertexData = otherVertexData;
  28835. source = meshes[index];
  28836. }
  28837. if (subdivideWithSubMeshes) {
  28838. indiceArray.push(meshes[index].getTotalIndices());
  28839. }
  28840. }
  28841. }
  28842. source = source;
  28843. if (!meshSubclass) {
  28844. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28845. }
  28846. vertexData.applyToMesh(meshSubclass);
  28847. // Setting properties
  28848. meshSubclass.material = source.material;
  28849. meshSubclass.checkCollisions = source.checkCollisions;
  28850. // Cleaning
  28851. if (disposeSource) {
  28852. for (index = 0; index < meshes.length; index++) {
  28853. if (meshes[index]) {
  28854. meshes[index].dispose();
  28855. }
  28856. }
  28857. }
  28858. // Subdivide
  28859. if (subdivideWithSubMeshes) {
  28860. //-- Suppresions du submesh global
  28861. meshSubclass.releaseSubMeshes();
  28862. index = 0;
  28863. var offset = 0;
  28864. //-- aplique la subdivision en fonction du tableau d'indices
  28865. while (index < indiceArray.length) {
  28866. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28867. offset += indiceArray[index];
  28868. index++;
  28869. }
  28870. }
  28871. return meshSubclass;
  28872. };
  28873. // Consts
  28874. Mesh._FRONTSIDE = 0;
  28875. Mesh._BACKSIDE = 1;
  28876. Mesh._DOUBLESIDE = 2;
  28877. Mesh._DEFAULTSIDE = 0;
  28878. Mesh._NO_CAP = 0;
  28879. Mesh._CAP_START = 1;
  28880. Mesh._CAP_END = 2;
  28881. Mesh._CAP_ALL = 3;
  28882. return Mesh;
  28883. }(BABYLON.AbstractMesh));
  28884. BABYLON.Mesh = Mesh;
  28885. })(BABYLON || (BABYLON = {}));
  28886. //# sourceMappingURL=babylon.mesh.js.map
  28887. var BABYLON;
  28888. (function (BABYLON) {
  28889. var BaseSubMesh = /** @class */ (function () {
  28890. function BaseSubMesh() {
  28891. }
  28892. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28893. get: function () {
  28894. return this._materialEffect;
  28895. },
  28896. enumerable: true,
  28897. configurable: true
  28898. });
  28899. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28900. if (defines === void 0) { defines = null; }
  28901. if (this._materialEffect === effect) {
  28902. if (!effect) {
  28903. this._materialDefines = null;
  28904. }
  28905. return;
  28906. }
  28907. this._materialDefines = defines;
  28908. this._materialEffect = effect;
  28909. };
  28910. return BaseSubMesh;
  28911. }());
  28912. BABYLON.BaseSubMesh = BaseSubMesh;
  28913. var SubMesh = /** @class */ (function (_super) {
  28914. __extends(SubMesh, _super);
  28915. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28916. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28917. var _this = _super.call(this) || this;
  28918. _this.materialIndex = materialIndex;
  28919. _this.verticesStart = verticesStart;
  28920. _this.verticesCount = verticesCount;
  28921. _this.indexStart = indexStart;
  28922. _this.indexCount = indexCount;
  28923. _this._renderId = 0;
  28924. _this._mesh = mesh;
  28925. _this._renderingMesh = renderingMesh || mesh;
  28926. mesh.subMeshes.push(_this);
  28927. _this._trianglePlanes = [];
  28928. _this._id = mesh.subMeshes.length - 1;
  28929. if (createBoundingBox) {
  28930. _this.refreshBoundingInfo();
  28931. mesh.computeWorldMatrix(true);
  28932. }
  28933. return _this;
  28934. }
  28935. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28936. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28937. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28938. };
  28939. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28940. get: function () {
  28941. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28942. },
  28943. enumerable: true,
  28944. configurable: true
  28945. });
  28946. /**
  28947. * Returns the submesh BoudingInfo object.
  28948. */
  28949. SubMesh.prototype.getBoundingInfo = function () {
  28950. if (this.IsGlobal) {
  28951. return this._mesh.getBoundingInfo();
  28952. }
  28953. return this._boundingInfo;
  28954. };
  28955. /**
  28956. * Sets the submesh BoundingInfo.
  28957. * Return the SubMesh.
  28958. */
  28959. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28960. this._boundingInfo = boundingInfo;
  28961. return this;
  28962. };
  28963. /**
  28964. * Returns the mesh of the current submesh.
  28965. */
  28966. SubMesh.prototype.getMesh = function () {
  28967. return this._mesh;
  28968. };
  28969. /**
  28970. * Returns the rendering mesh of the submesh.
  28971. */
  28972. SubMesh.prototype.getRenderingMesh = function () {
  28973. return this._renderingMesh;
  28974. };
  28975. /**
  28976. * Returns the submesh material.
  28977. */
  28978. SubMesh.prototype.getMaterial = function () {
  28979. var rootMaterial = this._renderingMesh.material;
  28980. if (rootMaterial === null || rootMaterial === undefined) {
  28981. return this._mesh.getScene().defaultMaterial;
  28982. }
  28983. else if (rootMaterial.getSubMaterial) {
  28984. var multiMaterial = rootMaterial;
  28985. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28986. if (this._currentMaterial !== effectiveMaterial) {
  28987. this._currentMaterial = effectiveMaterial;
  28988. this._materialDefines = null;
  28989. }
  28990. return effectiveMaterial;
  28991. }
  28992. return rootMaterial;
  28993. };
  28994. // Methods
  28995. /**
  28996. * Sets a new updated BoundingInfo object to the submesh.
  28997. * Returns the SubMesh.
  28998. */
  28999. SubMesh.prototype.refreshBoundingInfo = function () {
  29000. this._lastColliderWorldVertices = null;
  29001. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29002. return this;
  29003. }
  29004. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29005. if (!data) {
  29006. this._boundingInfo = this._mesh.getBoundingInfo();
  29007. return this;
  29008. }
  29009. var indices = this._renderingMesh.getIndices();
  29010. var extend;
  29011. //is this the only submesh?
  29012. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29013. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29014. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29015. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29016. }
  29017. else {
  29018. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29019. }
  29020. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29021. return this;
  29022. };
  29023. SubMesh.prototype._checkCollision = function (collider) {
  29024. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29025. return boundingInfo._checkCollision(collider);
  29026. };
  29027. /**
  29028. * Updates the submesh BoundingInfo.
  29029. * Returns the Submesh.
  29030. */
  29031. SubMesh.prototype.updateBoundingInfo = function (world) {
  29032. var boundingInfo = this.getBoundingInfo();
  29033. if (!boundingInfo) {
  29034. this.refreshBoundingInfo();
  29035. boundingInfo = this.getBoundingInfo();
  29036. }
  29037. boundingInfo.update(world);
  29038. return this;
  29039. };
  29040. /**
  29041. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29042. * Boolean returned.
  29043. */
  29044. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29045. var boundingInfo = this.getBoundingInfo();
  29046. if (!boundingInfo) {
  29047. return false;
  29048. }
  29049. return boundingInfo.isInFrustum(frustumPlanes);
  29050. };
  29051. /**
  29052. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29053. * Boolean returned.
  29054. */
  29055. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29056. var boundingInfo = this.getBoundingInfo();
  29057. if (!boundingInfo) {
  29058. return false;
  29059. }
  29060. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29061. };
  29062. /**
  29063. * Renders the submesh.
  29064. * Returns it.
  29065. */
  29066. SubMesh.prototype.render = function (enableAlphaMode) {
  29067. this._renderingMesh.render(this, enableAlphaMode);
  29068. return this;
  29069. };
  29070. /**
  29071. * Returns a new Index Buffer.
  29072. * Type returned : WebGLBuffer.
  29073. */
  29074. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29075. if (!this._linesIndexBuffer) {
  29076. var linesIndices = [];
  29077. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29078. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29079. }
  29080. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29081. this.linesIndexCount = linesIndices.length;
  29082. }
  29083. return this._linesIndexBuffer;
  29084. };
  29085. /**
  29086. * True is the passed Ray intersects the submesh bounding box.
  29087. * Boolean returned.
  29088. */
  29089. SubMesh.prototype.canIntersects = function (ray) {
  29090. var boundingInfo = this.getBoundingInfo();
  29091. if (!boundingInfo) {
  29092. return false;
  29093. }
  29094. return ray.intersectsBox(boundingInfo.boundingBox);
  29095. };
  29096. /**
  29097. * Returns an object IntersectionInfo.
  29098. */
  29099. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29100. var intersectInfo = null;
  29101. // LineMesh first as it's also a Mesh...
  29102. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29103. var lineMesh = this._mesh;
  29104. // Line test
  29105. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29106. var p0 = positions[indices[index]];
  29107. var p1 = positions[indices[index + 1]];
  29108. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29109. if (length < 0) {
  29110. continue;
  29111. }
  29112. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29113. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29114. if (fastCheck) {
  29115. break;
  29116. }
  29117. }
  29118. }
  29119. }
  29120. else {
  29121. // Triangles test
  29122. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29123. var p0 = positions[indices[index]];
  29124. var p1 = positions[indices[index + 1]];
  29125. var p2 = positions[indices[index + 2]];
  29126. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29127. if (currentIntersectInfo) {
  29128. if (currentIntersectInfo.distance < 0) {
  29129. continue;
  29130. }
  29131. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29132. intersectInfo = currentIntersectInfo;
  29133. intersectInfo.faceId = index / 3;
  29134. if (fastCheck) {
  29135. break;
  29136. }
  29137. }
  29138. }
  29139. }
  29140. }
  29141. return intersectInfo;
  29142. };
  29143. SubMesh.prototype._rebuild = function () {
  29144. if (this._linesIndexBuffer) {
  29145. this._linesIndexBuffer = null;
  29146. }
  29147. };
  29148. // Clone
  29149. /**
  29150. * Creates a new Submesh from the passed Mesh.
  29151. */
  29152. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29153. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29154. if (!this.IsGlobal) {
  29155. var boundingInfo = this.getBoundingInfo();
  29156. if (!boundingInfo) {
  29157. return result;
  29158. }
  29159. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29160. }
  29161. return result;
  29162. };
  29163. // Dispose
  29164. /**
  29165. * Disposes the Submesh.
  29166. * Returns nothing.
  29167. */
  29168. SubMesh.prototype.dispose = function () {
  29169. if (this._linesIndexBuffer) {
  29170. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29171. this._linesIndexBuffer = null;
  29172. }
  29173. // Remove from mesh
  29174. var index = this._mesh.subMeshes.indexOf(this);
  29175. this._mesh.subMeshes.splice(index, 1);
  29176. };
  29177. // Statics
  29178. /**
  29179. * Creates a new Submesh from the passed parameters :
  29180. * - materialIndex (integer) : the index of the main mesh material.
  29181. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29182. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29183. * - mesh (Mesh) : the main mesh to create the submesh from.
  29184. * - renderingMesh (optional Mesh) : rendering mesh.
  29185. */
  29186. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29187. var minVertexIndex = Number.MAX_VALUE;
  29188. var maxVertexIndex = -Number.MAX_VALUE;
  29189. renderingMesh = (renderingMesh || mesh);
  29190. var indices = renderingMesh.getIndices();
  29191. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29192. var vertexIndex = indices[index];
  29193. if (vertexIndex < minVertexIndex)
  29194. minVertexIndex = vertexIndex;
  29195. if (vertexIndex > maxVertexIndex)
  29196. maxVertexIndex = vertexIndex;
  29197. }
  29198. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29199. };
  29200. return SubMesh;
  29201. }(BaseSubMesh));
  29202. BABYLON.SubMesh = SubMesh;
  29203. })(BABYLON || (BABYLON = {}));
  29204. //# sourceMappingURL=babylon.subMesh.js.map
  29205. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29206. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29207. s = arguments[i];
  29208. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29209. t[p] = s[p];
  29210. }
  29211. return t;
  29212. };
  29213. var BABYLON;
  29214. (function (BABYLON) {
  29215. var MaterialDefines = /** @class */ (function () {
  29216. function MaterialDefines() {
  29217. this._isDirty = true;
  29218. this._areLightsDirty = true;
  29219. this._areAttributesDirty = true;
  29220. this._areTexturesDirty = true;
  29221. this._areFresnelDirty = true;
  29222. this._areMiscDirty = true;
  29223. this._areImageProcessingDirty = true;
  29224. this._normals = false;
  29225. this._uvs = false;
  29226. this._needNormals = false;
  29227. this._needUVs = false;
  29228. }
  29229. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29230. get: function () {
  29231. return this._isDirty;
  29232. },
  29233. enumerable: true,
  29234. configurable: true
  29235. });
  29236. MaterialDefines.prototype.markAsProcessed = function () {
  29237. this._isDirty = false;
  29238. this._areAttributesDirty = false;
  29239. this._areTexturesDirty = false;
  29240. this._areFresnelDirty = false;
  29241. this._areLightsDirty = false;
  29242. this._areMiscDirty = false;
  29243. this._areImageProcessingDirty = false;
  29244. };
  29245. MaterialDefines.prototype.markAsUnprocessed = function () {
  29246. this._isDirty = true;
  29247. };
  29248. MaterialDefines.prototype.markAllAsDirty = function () {
  29249. this._areTexturesDirty = true;
  29250. this._areAttributesDirty = true;
  29251. this._areLightsDirty = true;
  29252. this._areFresnelDirty = true;
  29253. this._areMiscDirty = true;
  29254. this._areImageProcessingDirty = true;
  29255. this._isDirty = true;
  29256. };
  29257. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29258. this._areImageProcessingDirty = true;
  29259. this._isDirty = true;
  29260. };
  29261. MaterialDefines.prototype.markAsLightDirty = function () {
  29262. this._areLightsDirty = true;
  29263. this._isDirty = true;
  29264. };
  29265. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29266. this._areAttributesDirty = true;
  29267. this._isDirty = true;
  29268. };
  29269. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29270. this._areTexturesDirty = true;
  29271. this._isDirty = true;
  29272. };
  29273. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29274. this._areFresnelDirty = true;
  29275. this._isDirty = true;
  29276. };
  29277. MaterialDefines.prototype.markAsMiscDirty = function () {
  29278. this._areMiscDirty = true;
  29279. this._isDirty = true;
  29280. };
  29281. MaterialDefines.prototype.rebuild = function () {
  29282. if (this._keys) {
  29283. delete this._keys;
  29284. }
  29285. this._keys = [];
  29286. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29287. var key = _a[_i];
  29288. if (key[0] === "_") {
  29289. continue;
  29290. }
  29291. this._keys.push(key);
  29292. }
  29293. };
  29294. MaterialDefines.prototype.isEqual = function (other) {
  29295. if (this._keys.length !== other._keys.length) {
  29296. return false;
  29297. }
  29298. for (var index = 0; index < this._keys.length; index++) {
  29299. var prop = this._keys[index];
  29300. if (this[prop] !== other[prop]) {
  29301. return false;
  29302. }
  29303. }
  29304. return true;
  29305. };
  29306. MaterialDefines.prototype.cloneTo = function (other) {
  29307. if (this._keys.length !== other._keys.length) {
  29308. other._keys = this._keys.slice(0);
  29309. }
  29310. for (var index = 0; index < this._keys.length; index++) {
  29311. var prop = this._keys[index];
  29312. other[prop] = this[prop];
  29313. }
  29314. };
  29315. MaterialDefines.prototype.reset = function () {
  29316. for (var index = 0; index < this._keys.length; index++) {
  29317. var prop = this._keys[index];
  29318. if (typeof (this[prop]) === "number") {
  29319. this[prop] = 0;
  29320. }
  29321. else {
  29322. this[prop] = false;
  29323. }
  29324. }
  29325. };
  29326. MaterialDefines.prototype.toString = function () {
  29327. var result = "";
  29328. for (var index = 0; index < this._keys.length; index++) {
  29329. var prop = this._keys[index];
  29330. var value = this[prop];
  29331. if (typeof (value) === "number") {
  29332. result += "#define " + prop + " " + this[prop] + "\n";
  29333. }
  29334. else if (value) {
  29335. result += "#define " + prop + "\n";
  29336. }
  29337. }
  29338. return result;
  29339. };
  29340. return MaterialDefines;
  29341. }());
  29342. BABYLON.MaterialDefines = MaterialDefines;
  29343. var Material = /** @class */ (function () {
  29344. function Material(name, scene, doNotAdd) {
  29345. this.checkReadyOnEveryCall = false;
  29346. this.checkReadyOnlyOnce = false;
  29347. this.state = "";
  29348. this._alpha = 1.0;
  29349. this._backFaceCulling = true;
  29350. this.doNotSerialize = false;
  29351. this.storeEffectOnSubMeshes = false;
  29352. /**
  29353. * An event triggered when the material is disposed.
  29354. * @type {BABYLON.Observable}
  29355. */
  29356. this.onDisposeObservable = new BABYLON.Observable();
  29357. /**
  29358. * An event triggered when the material is bound.
  29359. * @type {BABYLON.Observable}
  29360. */
  29361. this.onBindObservable = new BABYLON.Observable();
  29362. /**
  29363. * An event triggered when the material is unbound.
  29364. * @type {BABYLON.Observable}
  29365. */
  29366. this.onUnBindObservable = new BABYLON.Observable();
  29367. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29368. this._needDepthPrePass = false;
  29369. this.disableDepthWrite = false;
  29370. this.forceDepthWrite = false;
  29371. this.separateCullingPass = false;
  29372. this._fogEnabled = true;
  29373. this.pointSize = 1.0;
  29374. this.zOffset = 0;
  29375. this._wasPreviouslyReady = false;
  29376. this._fillMode = Material.TriangleFillMode;
  29377. this.name = name;
  29378. this.id = name || BABYLON.Tools.RandomId();
  29379. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29380. if (this._scene.useRightHandedSystem) {
  29381. this.sideOrientation = Material.ClockWiseSideOrientation;
  29382. }
  29383. else {
  29384. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29385. }
  29386. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29387. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29388. if (!doNotAdd) {
  29389. this._scene.materials.push(this);
  29390. }
  29391. }
  29392. Object.defineProperty(Material, "TriangleFillMode", {
  29393. get: function () {
  29394. return Material._TriangleFillMode;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(Material, "WireFrameFillMode", {
  29400. get: function () {
  29401. return Material._WireFrameFillMode;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. Object.defineProperty(Material, "PointFillMode", {
  29407. get: function () {
  29408. return Material._PointFillMode;
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(Material, "PointListDrawMode", {
  29414. get: function () {
  29415. return Material._PointListDrawMode;
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(Material, "LineListDrawMode", {
  29421. get: function () {
  29422. return Material._LineListDrawMode;
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(Material, "LineLoopDrawMode", {
  29428. get: function () {
  29429. return Material._LineLoopDrawMode;
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. Object.defineProperty(Material, "LineStripDrawMode", {
  29435. get: function () {
  29436. return Material._LineStripDrawMode;
  29437. },
  29438. enumerable: true,
  29439. configurable: true
  29440. });
  29441. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29442. get: function () {
  29443. return Material._TriangleStripDrawMode;
  29444. },
  29445. enumerable: true,
  29446. configurable: true
  29447. });
  29448. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29449. get: function () {
  29450. return Material._TriangleFanDrawMode;
  29451. },
  29452. enumerable: true,
  29453. configurable: true
  29454. });
  29455. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29456. get: function () {
  29457. return Material._ClockWiseSideOrientation;
  29458. },
  29459. enumerable: true,
  29460. configurable: true
  29461. });
  29462. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29463. get: function () {
  29464. return Material._CounterClockWiseSideOrientation;
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. Object.defineProperty(Material, "TextureDirtyFlag", {
  29470. get: function () {
  29471. return Material._TextureDirtyFlag;
  29472. },
  29473. enumerable: true,
  29474. configurable: true
  29475. });
  29476. Object.defineProperty(Material, "LightDirtyFlag", {
  29477. get: function () {
  29478. return Material._LightDirtyFlag;
  29479. },
  29480. enumerable: true,
  29481. configurable: true
  29482. });
  29483. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29484. get: function () {
  29485. return Material._FresnelDirtyFlag;
  29486. },
  29487. enumerable: true,
  29488. configurable: true
  29489. });
  29490. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29491. get: function () {
  29492. return Material._AttributesDirtyFlag;
  29493. },
  29494. enumerable: true,
  29495. configurable: true
  29496. });
  29497. Object.defineProperty(Material, "MiscDirtyFlag", {
  29498. get: function () {
  29499. return Material._MiscDirtyFlag;
  29500. },
  29501. enumerable: true,
  29502. configurable: true
  29503. });
  29504. Object.defineProperty(Material.prototype, "alpha", {
  29505. get: function () {
  29506. return this._alpha;
  29507. },
  29508. set: function (value) {
  29509. if (this._alpha === value) {
  29510. return;
  29511. }
  29512. this._alpha = value;
  29513. this.markAsDirty(Material.MiscDirtyFlag);
  29514. },
  29515. enumerable: true,
  29516. configurable: true
  29517. });
  29518. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29519. get: function () {
  29520. return this._backFaceCulling;
  29521. },
  29522. set: function (value) {
  29523. if (this._backFaceCulling === value) {
  29524. return;
  29525. }
  29526. this._backFaceCulling = value;
  29527. this.markAsDirty(Material.TextureDirtyFlag);
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. Object.defineProperty(Material.prototype, "onDispose", {
  29533. set: function (callback) {
  29534. if (this._onDisposeObserver) {
  29535. this.onDisposeObservable.remove(this._onDisposeObserver);
  29536. }
  29537. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. Object.defineProperty(Material.prototype, "onBind", {
  29543. set: function (callback) {
  29544. if (this._onBindObserver) {
  29545. this.onBindObservable.remove(this._onBindObserver);
  29546. }
  29547. this._onBindObserver = this.onBindObservable.add(callback);
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. Object.defineProperty(Material.prototype, "alphaMode", {
  29553. get: function () {
  29554. return this._alphaMode;
  29555. },
  29556. set: function (value) {
  29557. if (this._alphaMode === value) {
  29558. return;
  29559. }
  29560. this._alphaMode = value;
  29561. this.markAsDirty(Material.TextureDirtyFlag);
  29562. },
  29563. enumerable: true,
  29564. configurable: true
  29565. });
  29566. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29567. get: function () {
  29568. return this._needDepthPrePass;
  29569. },
  29570. set: function (value) {
  29571. if (this._needDepthPrePass === value) {
  29572. return;
  29573. }
  29574. this._needDepthPrePass = value;
  29575. if (this._needDepthPrePass) {
  29576. this.checkReadyOnEveryCall = true;
  29577. }
  29578. },
  29579. enumerable: true,
  29580. configurable: true
  29581. });
  29582. Object.defineProperty(Material.prototype, "fogEnabled", {
  29583. get: function () {
  29584. return this._fogEnabled;
  29585. },
  29586. set: function (value) {
  29587. if (this._fogEnabled === value) {
  29588. return;
  29589. }
  29590. this._fogEnabled = value;
  29591. this.markAsDirty(Material.MiscDirtyFlag);
  29592. },
  29593. enumerable: true,
  29594. configurable: true
  29595. });
  29596. Object.defineProperty(Material.prototype, "wireframe", {
  29597. get: function () {
  29598. return this._fillMode === Material.WireFrameFillMode;
  29599. },
  29600. set: function (value) {
  29601. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29602. },
  29603. enumerable: true,
  29604. configurable: true
  29605. });
  29606. Object.defineProperty(Material.prototype, "pointsCloud", {
  29607. get: function () {
  29608. return this._fillMode === Material.PointFillMode;
  29609. },
  29610. set: function (value) {
  29611. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. Object.defineProperty(Material.prototype, "fillMode", {
  29617. get: function () {
  29618. return this._fillMode;
  29619. },
  29620. set: function (value) {
  29621. if (this._fillMode === value) {
  29622. return;
  29623. }
  29624. this._fillMode = value;
  29625. this.markAsDirty(Material.MiscDirtyFlag);
  29626. },
  29627. enumerable: true,
  29628. configurable: true
  29629. });
  29630. /**
  29631. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29632. * subclasses should override adding information pertainent to themselves
  29633. */
  29634. Material.prototype.toString = function (fullDetails) {
  29635. var ret = "Name: " + this.name;
  29636. if (fullDetails) {
  29637. }
  29638. return ret;
  29639. };
  29640. /**
  29641. * Child classes can use it to update shaders
  29642. */
  29643. Material.prototype.getClassName = function () {
  29644. return "Material";
  29645. };
  29646. Object.defineProperty(Material.prototype, "isFrozen", {
  29647. get: function () {
  29648. return this.checkReadyOnlyOnce;
  29649. },
  29650. enumerable: true,
  29651. configurable: true
  29652. });
  29653. Material.prototype.freeze = function () {
  29654. this.checkReadyOnlyOnce = true;
  29655. };
  29656. Material.prototype.unfreeze = function () {
  29657. this.checkReadyOnlyOnce = false;
  29658. };
  29659. Material.prototype.isReady = function (mesh, useInstances) {
  29660. return true;
  29661. };
  29662. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29663. return false;
  29664. };
  29665. Material.prototype.getEffect = function () {
  29666. return this._effect;
  29667. };
  29668. Material.prototype.getScene = function () {
  29669. return this._scene;
  29670. };
  29671. Material.prototype.needAlphaBlending = function () {
  29672. return (this.alpha < 1.0);
  29673. };
  29674. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29675. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29676. };
  29677. Material.prototype.needAlphaTesting = function () {
  29678. return false;
  29679. };
  29680. Material.prototype.getAlphaTestTexture = function () {
  29681. return null;
  29682. };
  29683. Material.prototype.markDirty = function () {
  29684. this._wasPreviouslyReady = false;
  29685. };
  29686. Material.prototype._preBind = function (effect, overrideOrientation) {
  29687. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29688. var engine = this._scene.getEngine();
  29689. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29690. var reverse = orientation === Material.ClockWiseSideOrientation;
  29691. engine.enableEffect(effect ? effect : this._effect);
  29692. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29693. return reverse;
  29694. };
  29695. Material.prototype.bind = function (world, mesh) {
  29696. };
  29697. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29698. };
  29699. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29700. };
  29701. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29702. sceneUbo.bindToEffect(effect, "Scene");
  29703. };
  29704. Material.prototype.bindView = function (effect) {
  29705. if (!this._useUBO) {
  29706. effect.setMatrix("view", this.getScene().getViewMatrix());
  29707. }
  29708. else {
  29709. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29710. }
  29711. };
  29712. Material.prototype.bindViewProjection = function (effect) {
  29713. if (!this._useUBO) {
  29714. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29715. }
  29716. else {
  29717. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29718. }
  29719. };
  29720. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29721. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29722. };
  29723. Material.prototype._afterBind = function (mesh) {
  29724. this._scene._cachedMaterial = this;
  29725. if (mesh) {
  29726. this._scene._cachedVisibility = mesh.visibility;
  29727. }
  29728. else {
  29729. this._scene._cachedVisibility = 1;
  29730. }
  29731. if (mesh) {
  29732. this.onBindObservable.notifyObservers(mesh);
  29733. }
  29734. if (this.disableDepthWrite) {
  29735. var engine = this._scene.getEngine();
  29736. this._cachedDepthWriteState = engine.getDepthWrite();
  29737. engine.setDepthWrite(false);
  29738. }
  29739. };
  29740. Material.prototype.unbind = function () {
  29741. this.onUnBindObservable.notifyObservers(this);
  29742. if (this.disableDepthWrite) {
  29743. var engine = this._scene.getEngine();
  29744. engine.setDepthWrite(this._cachedDepthWriteState);
  29745. }
  29746. };
  29747. Material.prototype.getActiveTextures = function () {
  29748. return [];
  29749. };
  29750. Material.prototype.hasTexture = function (texture) {
  29751. return false;
  29752. };
  29753. Material.prototype.clone = function (name) {
  29754. return null;
  29755. };
  29756. Material.prototype.getBindedMeshes = function () {
  29757. var result = new Array();
  29758. for (var index = 0; index < this._scene.meshes.length; index++) {
  29759. var mesh = this._scene.meshes[index];
  29760. if (mesh.material === this) {
  29761. result.push(mesh);
  29762. }
  29763. }
  29764. return result;
  29765. };
  29766. /**
  29767. * Force shader compilation including textures ready check
  29768. */
  29769. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29770. var _this = this;
  29771. var localOptions = __assign({ clipPlane: false }, options);
  29772. var subMesh = new BABYLON.BaseSubMesh();
  29773. var scene = this.getScene();
  29774. var checkReady = function () {
  29775. if (!_this._scene || !_this._scene.getEngine()) {
  29776. return;
  29777. }
  29778. if (subMesh._materialDefines) {
  29779. subMesh._materialDefines._renderId = -1;
  29780. }
  29781. var clipPlaneState = scene.clipPlane;
  29782. if (localOptions.clipPlane) {
  29783. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29784. }
  29785. if (_this.storeEffectOnSubMeshes) {
  29786. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29787. if (onCompiled) {
  29788. onCompiled(_this);
  29789. }
  29790. }
  29791. else {
  29792. setTimeout(checkReady, 16);
  29793. }
  29794. }
  29795. else {
  29796. if (_this.isReady(mesh)) {
  29797. if (onCompiled) {
  29798. onCompiled(_this);
  29799. }
  29800. }
  29801. else {
  29802. setTimeout(checkReady, 16);
  29803. }
  29804. }
  29805. if (options && options.clipPlane) {
  29806. scene.clipPlane = clipPlaneState;
  29807. }
  29808. };
  29809. checkReady();
  29810. };
  29811. Material.prototype.markAsDirty = function (flag) {
  29812. if (flag & Material.TextureDirtyFlag) {
  29813. this._markAllSubMeshesAsTexturesDirty();
  29814. }
  29815. if (flag & Material.LightDirtyFlag) {
  29816. this._markAllSubMeshesAsLightsDirty();
  29817. }
  29818. if (flag & Material.FresnelDirtyFlag) {
  29819. this._markAllSubMeshesAsFresnelDirty();
  29820. }
  29821. if (flag & Material.AttributesDirtyFlag) {
  29822. this._markAllSubMeshesAsAttributesDirty();
  29823. }
  29824. if (flag & Material.MiscDirtyFlag) {
  29825. this._markAllSubMeshesAsMiscDirty();
  29826. }
  29827. this.getScene().resetCachedMaterial();
  29828. };
  29829. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29830. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29831. var mesh = _a[_i];
  29832. if (!mesh.subMeshes) {
  29833. continue;
  29834. }
  29835. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29836. var subMesh = _c[_b];
  29837. if (subMesh.getMaterial() !== this) {
  29838. continue;
  29839. }
  29840. if (!subMesh._materialDefines) {
  29841. continue;
  29842. }
  29843. func(subMesh._materialDefines);
  29844. }
  29845. }
  29846. };
  29847. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29848. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29849. };
  29850. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29851. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29852. };
  29853. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29854. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29855. };
  29856. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29857. this._markAllSubMeshesAsDirty(function (defines) {
  29858. defines.markAsFresnelDirty();
  29859. defines.markAsMiscDirty();
  29860. });
  29861. };
  29862. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29863. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29864. };
  29865. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29866. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29867. };
  29868. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29869. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29870. };
  29871. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29872. this._markAllSubMeshesAsDirty(function (defines) {
  29873. defines.markAsTexturesDirty();
  29874. defines.markAsMiscDirty();
  29875. });
  29876. };
  29877. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29878. // Animations
  29879. this.getScene().stopAnimation(this);
  29880. // Remove from scene
  29881. var index = this._scene.materials.indexOf(this);
  29882. if (index >= 0) {
  29883. this._scene.materials.splice(index, 1);
  29884. }
  29885. // Remove from meshes
  29886. for (index = 0; index < this._scene.meshes.length; index++) {
  29887. var mesh = this._scene.meshes[index];
  29888. if (mesh.material === this) {
  29889. mesh.material = null;
  29890. if (mesh.geometry) {
  29891. var geometry = (mesh.geometry);
  29892. if (this.storeEffectOnSubMeshes) {
  29893. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29894. var subMesh = _a[_i];
  29895. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29896. if (forceDisposeEffect && subMesh._materialEffect) {
  29897. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29898. }
  29899. }
  29900. }
  29901. else {
  29902. geometry._releaseVertexArrayObject(this._effect);
  29903. }
  29904. }
  29905. }
  29906. }
  29907. this._uniformBuffer.dispose();
  29908. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29909. if (forceDisposeEffect && this._effect) {
  29910. if (!this.storeEffectOnSubMeshes) {
  29911. this._scene.getEngine()._releaseEffect(this._effect);
  29912. }
  29913. this._effect = null;
  29914. }
  29915. // Callback
  29916. this.onDisposeObservable.notifyObservers(this);
  29917. this.onDisposeObservable.clear();
  29918. this.onBindObservable.clear();
  29919. this.onUnBindObservable.clear();
  29920. };
  29921. Material.prototype.serialize = function () {
  29922. return BABYLON.SerializationHelper.Serialize(this);
  29923. };
  29924. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29925. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29926. multiMaterial.id = parsedMultiMaterial.id;
  29927. if (BABYLON.Tags) {
  29928. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29929. }
  29930. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29931. var subMatId = parsedMultiMaterial.materials[matIndex];
  29932. if (subMatId) {
  29933. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29934. }
  29935. else {
  29936. multiMaterial.subMaterials.push(null);
  29937. }
  29938. }
  29939. return multiMaterial;
  29940. };
  29941. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29942. if (!parsedMaterial.customType) {
  29943. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29944. }
  29945. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29946. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29947. if (!BABYLON.LegacyPBRMaterial) {
  29948. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29949. return;
  29950. }
  29951. }
  29952. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29953. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29954. ;
  29955. };
  29956. // Triangle views
  29957. Material._TriangleFillMode = 0;
  29958. Material._WireFrameFillMode = 1;
  29959. Material._PointFillMode = 2;
  29960. // Draw modes
  29961. Material._PointListDrawMode = 3;
  29962. Material._LineListDrawMode = 4;
  29963. Material._LineLoopDrawMode = 5;
  29964. Material._LineStripDrawMode = 6;
  29965. Material._TriangleStripDrawMode = 7;
  29966. Material._TriangleFanDrawMode = 8;
  29967. Material._ClockWiseSideOrientation = 0;
  29968. Material._CounterClockWiseSideOrientation = 1;
  29969. Material._TextureDirtyFlag = 1;
  29970. Material._LightDirtyFlag = 2;
  29971. Material._FresnelDirtyFlag = 4;
  29972. Material._AttributesDirtyFlag = 8;
  29973. Material._MiscDirtyFlag = 16;
  29974. __decorate([
  29975. BABYLON.serialize()
  29976. ], Material.prototype, "id", void 0);
  29977. __decorate([
  29978. BABYLON.serialize()
  29979. ], Material.prototype, "name", void 0);
  29980. __decorate([
  29981. BABYLON.serialize()
  29982. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29983. __decorate([
  29984. BABYLON.serialize()
  29985. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29986. __decorate([
  29987. BABYLON.serialize()
  29988. ], Material.prototype, "state", void 0);
  29989. __decorate([
  29990. BABYLON.serialize("alpha")
  29991. ], Material.prototype, "_alpha", void 0);
  29992. __decorate([
  29993. BABYLON.serialize("backFaceCulling")
  29994. ], Material.prototype, "_backFaceCulling", void 0);
  29995. __decorate([
  29996. BABYLON.serialize()
  29997. ], Material.prototype, "sideOrientation", void 0);
  29998. __decorate([
  29999. BABYLON.serialize("alphaMode")
  30000. ], Material.prototype, "_alphaMode", void 0);
  30001. __decorate([
  30002. BABYLON.serialize()
  30003. ], Material.prototype, "_needDepthPrePass", void 0);
  30004. __decorate([
  30005. BABYLON.serialize()
  30006. ], Material.prototype, "disableDepthWrite", void 0);
  30007. __decorate([
  30008. BABYLON.serialize()
  30009. ], Material.prototype, "forceDepthWrite", void 0);
  30010. __decorate([
  30011. BABYLON.serialize()
  30012. ], Material.prototype, "separateCullingPass", void 0);
  30013. __decorate([
  30014. BABYLON.serialize("fogEnabled")
  30015. ], Material.prototype, "_fogEnabled", void 0);
  30016. __decorate([
  30017. BABYLON.serialize()
  30018. ], Material.prototype, "pointSize", void 0);
  30019. __decorate([
  30020. BABYLON.serialize()
  30021. ], Material.prototype, "zOffset", void 0);
  30022. __decorate([
  30023. BABYLON.serialize()
  30024. ], Material.prototype, "wireframe", null);
  30025. __decorate([
  30026. BABYLON.serialize()
  30027. ], Material.prototype, "pointsCloud", null);
  30028. __decorate([
  30029. BABYLON.serialize()
  30030. ], Material.prototype, "fillMode", null);
  30031. return Material;
  30032. }());
  30033. BABYLON.Material = Material;
  30034. })(BABYLON || (BABYLON = {}));
  30035. //# sourceMappingURL=babylon.material.js.map
  30036. var BABYLON;
  30037. (function (BABYLON) {
  30038. var UniformBuffer = /** @class */ (function () {
  30039. /**
  30040. * Uniform buffer objects.
  30041. *
  30042. * Handles blocks of uniform on the GPU.
  30043. *
  30044. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  30045. *
  30046. * For more information, please refer to :
  30047. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  30048. */
  30049. function UniformBuffer(engine, data, dynamic) {
  30050. this._engine = engine;
  30051. this._noUBO = !engine.supportsUniformBuffers;
  30052. this._dynamic = dynamic;
  30053. this._data = data || [];
  30054. this._uniformLocations = {};
  30055. this._uniformSizes = {};
  30056. this._uniformLocationPointer = 0;
  30057. this._needSync = false;
  30058. if (this._noUBO) {
  30059. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  30060. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  30061. this.updateFloat = this._updateFloatForEffect;
  30062. this.updateFloat2 = this._updateFloat2ForEffect;
  30063. this.updateFloat3 = this._updateFloat3ForEffect;
  30064. this.updateFloat4 = this._updateFloat4ForEffect;
  30065. this.updateMatrix = this._updateMatrixForEffect;
  30066. this.updateVector3 = this._updateVector3ForEffect;
  30067. this.updateVector4 = this._updateVector4ForEffect;
  30068. this.updateColor3 = this._updateColor3ForEffect;
  30069. this.updateColor4 = this._updateColor4ForEffect;
  30070. }
  30071. else {
  30072. this._engine._uniformBuffers.push(this);
  30073. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  30074. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  30075. this.updateFloat = this._updateFloatForUniform;
  30076. this.updateFloat2 = this._updateFloat2ForUniform;
  30077. this.updateFloat3 = this._updateFloat3ForUniform;
  30078. this.updateFloat4 = this._updateFloat4ForUniform;
  30079. this.updateMatrix = this._updateMatrixForUniform;
  30080. this.updateVector3 = this._updateVector3ForUniform;
  30081. this.updateVector4 = this._updateVector4ForUniform;
  30082. this.updateColor3 = this._updateColor3ForUniform;
  30083. this.updateColor4 = this._updateColor4ForUniform;
  30084. }
  30085. }
  30086. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  30087. // Properties
  30088. /**
  30089. * Indicates if the buffer is using the WebGL2 UBO implementation,
  30090. * or just falling back on setUniformXXX calls.
  30091. */
  30092. get: function () {
  30093. return !this._noUBO;
  30094. },
  30095. enumerable: true,
  30096. configurable: true
  30097. });
  30098. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  30099. /**
  30100. * Indicates if the WebGL underlying uniform buffer is in sync
  30101. * with the javascript cache data.
  30102. */
  30103. get: function () {
  30104. return !this._needSync;
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. /**
  30110. * Indicates if the WebGL underlying uniform buffer is dynamic.
  30111. * Also, a dynamic UniformBuffer will disable cache verification and always
  30112. * update the underlying WebGL uniform buffer to the GPU.
  30113. */
  30114. UniformBuffer.prototype.isDynamic = function () {
  30115. return this._dynamic !== undefined;
  30116. };
  30117. /**
  30118. * The data cache on JS side.
  30119. */
  30120. UniformBuffer.prototype.getData = function () {
  30121. return this._bufferData;
  30122. };
  30123. /**
  30124. * The underlying WebGL Uniform buffer.
  30125. */
  30126. UniformBuffer.prototype.getBuffer = function () {
  30127. return this._buffer;
  30128. };
  30129. /**
  30130. * std140 layout specifies how to align data within an UBO structure.
  30131. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  30132. * for specs.
  30133. */
  30134. UniformBuffer.prototype._fillAlignment = function (size) {
  30135. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  30136. // and 4x4 matrices
  30137. // TODO : change if other types are used
  30138. var alignment;
  30139. if (size <= 2) {
  30140. alignment = size;
  30141. }
  30142. else {
  30143. alignment = 4;
  30144. }
  30145. if ((this._uniformLocationPointer % alignment) !== 0) {
  30146. var oldPointer = this._uniformLocationPointer;
  30147. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30148. var diff = this._uniformLocationPointer - oldPointer;
  30149. for (var i = 0; i < diff; i++) {
  30150. this._data.push(0);
  30151. }
  30152. }
  30153. };
  30154. /**
  30155. * Adds an uniform in the buffer.
  30156. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30157. * for the layout to be correct !
  30158. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30159. * @param {number|number[]} size Data size, or data directly.
  30160. */
  30161. UniformBuffer.prototype.addUniform = function (name, size) {
  30162. if (this._noUBO) {
  30163. return;
  30164. }
  30165. if (this._uniformLocations[name] !== undefined) {
  30166. // Already existing uniform
  30167. return;
  30168. }
  30169. // This function must be called in the order of the shader layout !
  30170. // size can be the size of the uniform, or data directly
  30171. var data;
  30172. if (size instanceof Array) {
  30173. data = size;
  30174. size = data.length;
  30175. }
  30176. else {
  30177. size = size;
  30178. data = [];
  30179. // Fill with zeros
  30180. for (var i = 0; i < size; i++) {
  30181. data.push(0);
  30182. }
  30183. }
  30184. this._fillAlignment(size);
  30185. this._uniformSizes[name] = size;
  30186. this._uniformLocations[name] = this._uniformLocationPointer;
  30187. this._uniformLocationPointer += size;
  30188. for (var i = 0; i < size; i++) {
  30189. this._data.push(data[i]);
  30190. }
  30191. this._needSync = true;
  30192. };
  30193. /**
  30194. * Wrapper for addUniform.
  30195. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30196. * @param {Matrix} mat A 4x4 matrix.
  30197. */
  30198. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30199. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30200. };
  30201. /**
  30202. * Wrapper for addUniform.
  30203. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30204. * @param {number} x
  30205. * @param {number} y
  30206. */
  30207. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30208. var temp = [x, y];
  30209. this.addUniform(name, temp);
  30210. };
  30211. /**
  30212. * Wrapper for addUniform.
  30213. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30214. * @param {number} x
  30215. * @param {number} y
  30216. * @param {number} z
  30217. */
  30218. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30219. var temp = [x, y, z];
  30220. this.addUniform(name, temp);
  30221. };
  30222. /**
  30223. * Wrapper for addUniform.
  30224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30225. * @param {Color3} color
  30226. */
  30227. UniformBuffer.prototype.addColor3 = function (name, color) {
  30228. var temp = new Array();
  30229. color.toArray(temp);
  30230. this.addUniform(name, temp);
  30231. };
  30232. /**
  30233. * Wrapper for addUniform.
  30234. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30235. * @param {Color3} color
  30236. * @param {number} alpha
  30237. */
  30238. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30239. var temp = new Array();
  30240. color.toArray(temp);
  30241. temp.push(alpha);
  30242. this.addUniform(name, temp);
  30243. };
  30244. /**
  30245. * Wrapper for addUniform.
  30246. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30247. * @param {Vector3} vector
  30248. */
  30249. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30250. var temp = new Array();
  30251. vector.toArray(temp);
  30252. this.addUniform(name, temp);
  30253. };
  30254. /**
  30255. * Wrapper for addUniform.
  30256. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30257. */
  30258. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30259. this.addUniform(name, 12);
  30260. };
  30261. /**
  30262. * Wrapper for addUniform.
  30263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30264. */
  30265. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30266. this.addUniform(name, 8);
  30267. };
  30268. /**
  30269. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30270. */
  30271. UniformBuffer.prototype.create = function () {
  30272. if (this._noUBO) {
  30273. return;
  30274. }
  30275. if (this._buffer) {
  30276. return; // nothing to do
  30277. }
  30278. // See spec, alignment must be filled as a vec4
  30279. this._fillAlignment(4);
  30280. this._bufferData = new Float32Array(this._data);
  30281. this._rebuild();
  30282. this._needSync = true;
  30283. };
  30284. UniformBuffer.prototype._rebuild = function () {
  30285. if (this._noUBO) {
  30286. return;
  30287. }
  30288. if (this._dynamic) {
  30289. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30290. }
  30291. else {
  30292. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30293. }
  30294. };
  30295. /**
  30296. * Updates the WebGL Uniform Buffer on the GPU.
  30297. * If the `dynamic` flag is set to true, no cache comparison is done.
  30298. * Otherwise, the buffer will be updated only if the cache differs.
  30299. */
  30300. UniformBuffer.prototype.update = function () {
  30301. if (!this._buffer) {
  30302. this.create();
  30303. return;
  30304. }
  30305. if (!this._dynamic && !this._needSync) {
  30306. return;
  30307. }
  30308. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30309. this._needSync = false;
  30310. };
  30311. /**
  30312. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30313. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30314. * @param {number[]|Float32Array} data Flattened data
  30315. * @param {number} size Size of the data.
  30316. */
  30317. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30318. var location = this._uniformLocations[uniformName];
  30319. if (location === undefined) {
  30320. if (this._buffer) {
  30321. // Cannot add an uniform if the buffer is already created
  30322. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30323. return;
  30324. }
  30325. this.addUniform(uniformName, size);
  30326. location = this._uniformLocations[uniformName];
  30327. }
  30328. if (!this._buffer) {
  30329. this.create();
  30330. }
  30331. if (!this._dynamic) {
  30332. // Cache for static uniform buffers
  30333. var changed = false;
  30334. for (var i = 0; i < size; i++) {
  30335. if (this._bufferData[location + i] !== data[i]) {
  30336. changed = true;
  30337. this._bufferData[location + i] = data[i];
  30338. }
  30339. }
  30340. this._needSync = this._needSync || changed;
  30341. }
  30342. else {
  30343. // No cache for dynamic
  30344. for (var i = 0; i < size; i++) {
  30345. this._bufferData[location + i] = data[i];
  30346. }
  30347. }
  30348. };
  30349. // Update methods
  30350. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30351. // To match std140, matrix must be realigned
  30352. for (var i = 0; i < 3; i++) {
  30353. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30354. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30355. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30356. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30357. }
  30358. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30359. };
  30360. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30361. this._currentEffect.setMatrix3x3(name, matrix);
  30362. };
  30363. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30364. this._currentEffect.setMatrix2x2(name, matrix);
  30365. };
  30366. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30367. // To match std140, matrix must be realigned
  30368. for (var i = 0; i < 2; i++) {
  30369. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30370. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30371. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30372. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30373. }
  30374. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30375. };
  30376. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30377. this._currentEffect.setFloat(name, x);
  30378. };
  30379. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30380. UniformBuffer._tempBuffer[0] = x;
  30381. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30382. };
  30383. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30384. if (suffix === void 0) { suffix = ""; }
  30385. this._currentEffect.setFloat2(name + suffix, x, y);
  30386. };
  30387. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30388. if (suffix === void 0) { suffix = ""; }
  30389. UniformBuffer._tempBuffer[0] = x;
  30390. UniformBuffer._tempBuffer[1] = y;
  30391. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30392. };
  30393. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30394. if (suffix === void 0) { suffix = ""; }
  30395. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30396. };
  30397. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30398. if (suffix === void 0) { suffix = ""; }
  30399. UniformBuffer._tempBuffer[0] = x;
  30400. UniformBuffer._tempBuffer[1] = y;
  30401. UniformBuffer._tempBuffer[2] = z;
  30402. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30403. };
  30404. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30405. if (suffix === void 0) { suffix = ""; }
  30406. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30407. };
  30408. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30409. if (suffix === void 0) { suffix = ""; }
  30410. UniformBuffer._tempBuffer[0] = x;
  30411. UniformBuffer._tempBuffer[1] = y;
  30412. UniformBuffer._tempBuffer[2] = z;
  30413. UniformBuffer._tempBuffer[3] = w;
  30414. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30415. };
  30416. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30417. this._currentEffect.setMatrix(name, mat);
  30418. };
  30419. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30420. this.updateUniform(name, mat.toArray(), 16);
  30421. };
  30422. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30423. this._currentEffect.setVector3(name, vector);
  30424. };
  30425. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30426. vector.toArray(UniformBuffer._tempBuffer);
  30427. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30428. };
  30429. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30430. this._currentEffect.setVector4(name, vector);
  30431. };
  30432. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30433. vector.toArray(UniformBuffer._tempBuffer);
  30434. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30435. };
  30436. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30437. if (suffix === void 0) { suffix = ""; }
  30438. this._currentEffect.setColor3(name + suffix, color);
  30439. };
  30440. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30441. if (suffix === void 0) { suffix = ""; }
  30442. color.toArray(UniformBuffer._tempBuffer);
  30443. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30444. };
  30445. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30446. if (suffix === void 0) { suffix = ""; }
  30447. this._currentEffect.setColor4(name + suffix, color, alpha);
  30448. };
  30449. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30450. if (suffix === void 0) { suffix = ""; }
  30451. color.toArray(UniformBuffer._tempBuffer);
  30452. UniformBuffer._tempBuffer[3] = alpha;
  30453. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30454. };
  30455. /**
  30456. * Sets a sampler uniform on the effect.
  30457. * @param {string} name Name of the sampler.
  30458. * @param {Texture} texture
  30459. */
  30460. UniformBuffer.prototype.setTexture = function (name, texture) {
  30461. this._currentEffect.setTexture(name, texture);
  30462. };
  30463. /**
  30464. * Directly updates the value of the uniform in the cache AND on the GPU.
  30465. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30466. * @param {number[]|Float32Array} data Flattened data
  30467. */
  30468. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30469. this.updateUniform(uniformName, data, data.length);
  30470. this.update();
  30471. };
  30472. /**
  30473. * Binds this uniform buffer to an effect.
  30474. * @param {Effect} effect
  30475. * @param {string} name Name of the uniform block in the shader.
  30476. */
  30477. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30478. this._currentEffect = effect;
  30479. if (this._noUBO || !this._buffer) {
  30480. return;
  30481. }
  30482. effect.bindUniformBuffer(this._buffer, name);
  30483. };
  30484. /**
  30485. * Disposes the uniform buffer.
  30486. */
  30487. UniformBuffer.prototype.dispose = function () {
  30488. if (this._noUBO) {
  30489. return;
  30490. }
  30491. var index = this._engine._uniformBuffers.indexOf(this);
  30492. if (index !== -1) {
  30493. this._engine._uniformBuffers.splice(index, 1);
  30494. }
  30495. if (!this._buffer) {
  30496. return;
  30497. }
  30498. if (this._engine._releaseBuffer(this._buffer)) {
  30499. this._buffer = null;
  30500. }
  30501. };
  30502. // Pool for avoiding memory leaks
  30503. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30504. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30505. return UniformBuffer;
  30506. }());
  30507. BABYLON.UniformBuffer = UniformBuffer;
  30508. })(BABYLON || (BABYLON = {}));
  30509. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30510. var BABYLON;
  30511. (function (BABYLON) {
  30512. var VertexData = /** @class */ (function () {
  30513. function VertexData() {
  30514. }
  30515. VertexData.prototype.set = function (data, kind) {
  30516. switch (kind) {
  30517. case BABYLON.VertexBuffer.PositionKind:
  30518. this.positions = data;
  30519. break;
  30520. case BABYLON.VertexBuffer.NormalKind:
  30521. this.normals = data;
  30522. break;
  30523. case BABYLON.VertexBuffer.TangentKind:
  30524. this.tangents = data;
  30525. break;
  30526. case BABYLON.VertexBuffer.UVKind:
  30527. this.uvs = data;
  30528. break;
  30529. case BABYLON.VertexBuffer.UV2Kind:
  30530. this.uvs2 = data;
  30531. break;
  30532. case BABYLON.VertexBuffer.UV3Kind:
  30533. this.uvs3 = data;
  30534. break;
  30535. case BABYLON.VertexBuffer.UV4Kind:
  30536. this.uvs4 = data;
  30537. break;
  30538. case BABYLON.VertexBuffer.UV5Kind:
  30539. this.uvs5 = data;
  30540. break;
  30541. case BABYLON.VertexBuffer.UV6Kind:
  30542. this.uvs6 = data;
  30543. break;
  30544. case BABYLON.VertexBuffer.ColorKind:
  30545. this.colors = data;
  30546. break;
  30547. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30548. this.matricesIndices = data;
  30549. break;
  30550. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30551. this.matricesWeights = data;
  30552. break;
  30553. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30554. this.matricesIndicesExtra = data;
  30555. break;
  30556. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30557. this.matricesWeightsExtra = data;
  30558. break;
  30559. }
  30560. };
  30561. /**
  30562. * Associates the vertexData to the passed Mesh.
  30563. * Sets it as updatable or not (default `false`).
  30564. * Returns the VertexData.
  30565. */
  30566. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30567. this._applyTo(mesh, updatable);
  30568. return this;
  30569. };
  30570. /**
  30571. * Associates the vertexData to the passed Geometry.
  30572. * Sets it as updatable or not (default `false`).
  30573. * Returns the VertexData.
  30574. */
  30575. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30576. this._applyTo(geometry, updatable);
  30577. return this;
  30578. };
  30579. /**
  30580. * Updates the associated mesh.
  30581. * Returns the VertexData.
  30582. */
  30583. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30584. this._update(mesh);
  30585. return this;
  30586. };
  30587. /**
  30588. * Updates the associated geometry.
  30589. * Returns the VertexData.
  30590. */
  30591. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30592. this._update(geometry);
  30593. return this;
  30594. };
  30595. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30596. if (updatable === void 0) { updatable = false; }
  30597. if (this.positions) {
  30598. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30599. }
  30600. if (this.normals) {
  30601. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30602. }
  30603. if (this.tangents) {
  30604. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30605. }
  30606. if (this.uvs) {
  30607. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30608. }
  30609. if (this.uvs2) {
  30610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30611. }
  30612. if (this.uvs3) {
  30613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30614. }
  30615. if (this.uvs4) {
  30616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30617. }
  30618. if (this.uvs5) {
  30619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30620. }
  30621. if (this.uvs6) {
  30622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30623. }
  30624. if (this.colors) {
  30625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30626. }
  30627. if (this.matricesIndices) {
  30628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30629. }
  30630. if (this.matricesWeights) {
  30631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30632. }
  30633. if (this.matricesIndicesExtra) {
  30634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30635. }
  30636. if (this.matricesWeightsExtra) {
  30637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30638. }
  30639. if (this.indices) {
  30640. meshOrGeometry.setIndices(this.indices, null, updatable);
  30641. }
  30642. return this;
  30643. };
  30644. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30645. if (this.positions) {
  30646. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30647. }
  30648. if (this.normals) {
  30649. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30650. }
  30651. if (this.tangents) {
  30652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30653. }
  30654. if (this.uvs) {
  30655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30656. }
  30657. if (this.uvs2) {
  30658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30659. }
  30660. if (this.uvs3) {
  30661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30662. }
  30663. if (this.uvs4) {
  30664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30665. }
  30666. if (this.uvs5) {
  30667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30668. }
  30669. if (this.uvs6) {
  30670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30671. }
  30672. if (this.colors) {
  30673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30674. }
  30675. if (this.matricesIndices) {
  30676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30677. }
  30678. if (this.matricesWeights) {
  30679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30680. }
  30681. if (this.matricesIndicesExtra) {
  30682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30683. }
  30684. if (this.matricesWeightsExtra) {
  30685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30686. }
  30687. if (this.indices) {
  30688. meshOrGeometry.setIndices(this.indices, null);
  30689. }
  30690. return this;
  30691. };
  30692. /**
  30693. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30694. * Returns the VertexData.
  30695. */
  30696. VertexData.prototype.transform = function (matrix) {
  30697. var transformed = BABYLON.Vector3.Zero();
  30698. var index;
  30699. if (this.positions) {
  30700. var position = BABYLON.Vector3.Zero();
  30701. for (index = 0; index < this.positions.length; index += 3) {
  30702. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30703. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30704. this.positions[index] = transformed.x;
  30705. this.positions[index + 1] = transformed.y;
  30706. this.positions[index + 2] = transformed.z;
  30707. }
  30708. }
  30709. if (this.normals) {
  30710. var normal = BABYLON.Vector3.Zero();
  30711. for (index = 0; index < this.normals.length; index += 3) {
  30712. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30713. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30714. this.normals[index] = transformed.x;
  30715. this.normals[index + 1] = transformed.y;
  30716. this.normals[index + 2] = transformed.z;
  30717. }
  30718. }
  30719. if (this.tangents) {
  30720. var tangent = BABYLON.Vector4.Zero();
  30721. var tangentTransformed = BABYLON.Vector4.Zero();
  30722. for (index = 0; index < this.tangents.length; index += 4) {
  30723. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30724. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30725. this.tangents[index] = tangentTransformed.x;
  30726. this.tangents[index + 1] = tangentTransformed.y;
  30727. this.tangents[index + 2] = tangentTransformed.z;
  30728. this.tangents[index + 3] = tangentTransformed.w;
  30729. }
  30730. }
  30731. return this;
  30732. };
  30733. /**
  30734. * Merges the passed VertexData into the current one.
  30735. * Returns the modified VertexData.
  30736. */
  30737. VertexData.prototype.merge = function (other, options) {
  30738. options = options || {};
  30739. if (other.indices) {
  30740. if (!this.indices) {
  30741. this.indices = [];
  30742. }
  30743. var offset = this.positions ? this.positions.length / 3 : 0;
  30744. for (var index = 0; index < other.indices.length; index++) {
  30745. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30746. this.indices.push(other.indices[index] + offset);
  30747. }
  30748. }
  30749. this.positions = this._mergeElement(this.positions, other.positions);
  30750. if (!this.positions) {
  30751. return this;
  30752. }
  30753. var count = this.positions.length / 3;
  30754. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30755. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30756. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30757. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30758. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30759. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30760. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30761. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30762. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30763. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30764. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30765. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30766. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30767. return this;
  30768. };
  30769. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30770. if (length === void 0) { length = 0; }
  30771. if (defaultValue === void 0) { defaultValue = 0; }
  30772. if (!other && !source) {
  30773. return null;
  30774. }
  30775. if (!other) {
  30776. var padding = new Float32Array(source.length);
  30777. padding.fill(defaultValue);
  30778. return this._mergeElement(source, padding, length);
  30779. }
  30780. if (!source) {
  30781. if (length === 0 || length === other.length) {
  30782. return other;
  30783. }
  30784. var padding = new Float32Array(length - other.length);
  30785. padding.fill(defaultValue);
  30786. return this._mergeElement(padding, other, length);
  30787. }
  30788. var len = other.length + source.length;
  30789. var isSrcTypedArray = source instanceof Float32Array;
  30790. var isOthTypedArray = other instanceof Float32Array;
  30791. // use non-loop method when the source is Float32Array
  30792. if (isSrcTypedArray) {
  30793. var ret32 = new Float32Array(len);
  30794. ret32.set(source);
  30795. ret32.set(other, source.length);
  30796. return ret32;
  30797. // source is number[], when other is also use concat
  30798. }
  30799. else if (!isOthTypedArray) {
  30800. return source.concat(other);
  30801. // source is a number[], but other is a Float32Array, loop required
  30802. }
  30803. else {
  30804. var ret = source.slice(0); // copy source to a separate array
  30805. for (var i = 0, len = other.length; i < len; i++) {
  30806. ret.push(other[i]);
  30807. }
  30808. return ret;
  30809. }
  30810. };
  30811. /**
  30812. * Serializes the VertexData.
  30813. * Returns a serialized object.
  30814. */
  30815. VertexData.prototype.serialize = function () {
  30816. var serializationObject = this.serialize();
  30817. if (this.positions) {
  30818. serializationObject.positions = this.positions;
  30819. }
  30820. if (this.normals) {
  30821. serializationObject.normals = this.normals;
  30822. }
  30823. if (this.tangents) {
  30824. serializationObject.tangents = this.tangents;
  30825. }
  30826. if (this.uvs) {
  30827. serializationObject.uvs = this.uvs;
  30828. }
  30829. if (this.uvs2) {
  30830. serializationObject.uvs2 = this.uvs2;
  30831. }
  30832. if (this.uvs3) {
  30833. serializationObject.uvs3 = this.uvs3;
  30834. }
  30835. if (this.uvs4) {
  30836. serializationObject.uvs4 = this.uvs4;
  30837. }
  30838. if (this.uvs5) {
  30839. serializationObject.uvs5 = this.uvs5;
  30840. }
  30841. if (this.uvs6) {
  30842. serializationObject.uvs6 = this.uvs6;
  30843. }
  30844. if (this.colors) {
  30845. serializationObject.colors = this.colors;
  30846. }
  30847. if (this.matricesIndices) {
  30848. serializationObject.matricesIndices = this.matricesIndices;
  30849. serializationObject.matricesIndices._isExpanded = true;
  30850. }
  30851. if (this.matricesWeights) {
  30852. serializationObject.matricesWeights = this.matricesWeights;
  30853. }
  30854. if (this.matricesIndicesExtra) {
  30855. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30856. serializationObject.matricesIndicesExtra._isExpanded = true;
  30857. }
  30858. if (this.matricesWeightsExtra) {
  30859. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30860. }
  30861. serializationObject.indices = this.indices;
  30862. return serializationObject;
  30863. };
  30864. // Statics
  30865. /**
  30866. * Returns the object VertexData associated to the passed mesh.
  30867. */
  30868. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30869. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30870. };
  30871. /**
  30872. * Returns the object VertexData associated to the passed geometry.
  30873. */
  30874. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30875. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30876. };
  30877. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30878. var result = new VertexData();
  30879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30880. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30881. }
  30882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30883. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30884. }
  30885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30886. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30887. }
  30888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30889. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30890. }
  30891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30892. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30893. }
  30894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30895. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30896. }
  30897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30898. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30899. }
  30900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30901. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30902. }
  30903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30904. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30905. }
  30906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30907. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30908. }
  30909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30910. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30911. }
  30912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30913. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30914. }
  30915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30916. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30917. }
  30918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30919. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30920. }
  30921. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30922. return result;
  30923. };
  30924. /**
  30925. * Creates the vertexData of the Ribbon.
  30926. */
  30927. VertexData.CreateRibbon = function (options) {
  30928. var pathArray = options.pathArray;
  30929. var closeArray = options.closeArray || false;
  30930. var closePath = options.closePath || false;
  30931. var invertUV = options.invertUV || false;
  30932. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30933. var offset = options.offset || defaultOffset;
  30934. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30935. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30936. var customUV = options.uvs;
  30937. var customColors = options.colors;
  30938. var positions = [];
  30939. var indices = [];
  30940. var normals = [];
  30941. var uvs = [];
  30942. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30943. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30944. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30945. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30946. var minlg; // minimal length among all paths from pathArray
  30947. var lg = []; // array of path lengths : nb of vertex per path
  30948. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30949. var p; // path iterator
  30950. var i; // point iterator
  30951. var j; // point iterator
  30952. // if single path in pathArray
  30953. if (pathArray.length < 2) {
  30954. var ar1 = [];
  30955. var ar2 = [];
  30956. for (i = 0; i < pathArray[0].length - offset; i++) {
  30957. ar1.push(pathArray[0][i]);
  30958. ar2.push(pathArray[0][i + offset]);
  30959. }
  30960. pathArray = [ar1, ar2];
  30961. }
  30962. // positions and horizontal distances (u)
  30963. var idc = 0;
  30964. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30965. var path;
  30966. var l;
  30967. minlg = pathArray[0].length;
  30968. var vectlg;
  30969. var dist;
  30970. for (p = 0; p < pathArray.length; p++) {
  30971. uTotalDistance[p] = 0;
  30972. us[p] = [0];
  30973. path = pathArray[p];
  30974. l = path.length;
  30975. minlg = (minlg < l) ? minlg : l;
  30976. j = 0;
  30977. while (j < l) {
  30978. positions.push(path[j].x, path[j].y, path[j].z);
  30979. if (j > 0) {
  30980. vectlg = path[j].subtract(path[j - 1]).length();
  30981. dist = vectlg + uTotalDistance[p];
  30982. us[p].push(dist);
  30983. uTotalDistance[p] = dist;
  30984. }
  30985. j++;
  30986. }
  30987. if (closePath) {
  30988. j--;
  30989. positions.push(path[0].x, path[0].y, path[0].z);
  30990. vectlg = path[j].subtract(path[0]).length();
  30991. dist = vectlg + uTotalDistance[p];
  30992. us[p].push(dist);
  30993. uTotalDistance[p] = dist;
  30994. }
  30995. lg[p] = l + closePathCorr;
  30996. idx[p] = idc;
  30997. idc += (l + closePathCorr);
  30998. }
  30999. // vertical distances (v)
  31000. var path1;
  31001. var path2;
  31002. var vertex1 = null;
  31003. var vertex2 = null;
  31004. for (i = 0; i < minlg + closePathCorr; i++) {
  31005. vTotalDistance[i] = 0;
  31006. vs[i] = [0];
  31007. for (p = 0; p < pathArray.length - 1; p++) {
  31008. path1 = pathArray[p];
  31009. path2 = pathArray[p + 1];
  31010. if (i === minlg) {
  31011. vertex1 = path1[0];
  31012. vertex2 = path2[0];
  31013. }
  31014. else {
  31015. vertex1 = path1[i];
  31016. vertex2 = path2[i];
  31017. }
  31018. vectlg = vertex2.subtract(vertex1).length();
  31019. dist = vectlg + vTotalDistance[i];
  31020. vs[i].push(dist);
  31021. vTotalDistance[i] = dist;
  31022. }
  31023. if (closeArray && vertex2 && vertex1) {
  31024. path1 = pathArray[p];
  31025. path2 = pathArray[0];
  31026. if (i === minlg) {
  31027. vertex2 = path2[0];
  31028. }
  31029. vectlg = vertex2.subtract(vertex1).length();
  31030. dist = vectlg + vTotalDistance[i];
  31031. vTotalDistance[i] = dist;
  31032. }
  31033. }
  31034. // uvs
  31035. var u;
  31036. var v;
  31037. if (customUV) {
  31038. for (p = 0; p < customUV.length; p++) {
  31039. uvs.push(customUV[p].x, customUV[p].y);
  31040. }
  31041. }
  31042. else {
  31043. for (p = 0; p < pathArray.length; p++) {
  31044. for (i = 0; i < minlg + closePathCorr; i++) {
  31045. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  31046. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  31047. if (invertUV) {
  31048. uvs.push(v, u);
  31049. }
  31050. else {
  31051. uvs.push(u, v);
  31052. }
  31053. }
  31054. }
  31055. }
  31056. // indices
  31057. p = 0; // path index
  31058. var pi = 0; // positions array index
  31059. var l1 = lg[p] - 1; // path1 length
  31060. var l2 = lg[p + 1] - 1; // path2 length
  31061. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31062. var shft = idx[1] - idx[0]; // shift
  31063. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31064. while (pi <= min && p < path1nb) {
  31065. // 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
  31066. indices.push(pi, pi + shft, pi + 1);
  31067. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31068. pi += 1;
  31069. if (pi === min) {
  31070. p++;
  31071. if (p === lg.length - 1) {
  31072. shft = idx[0] - idx[p];
  31073. l1 = lg[p] - 1;
  31074. l2 = lg[0] - 1;
  31075. }
  31076. else {
  31077. shft = idx[p + 1] - idx[p];
  31078. l1 = lg[p] - 1;
  31079. l2 = lg[p + 1] - 1;
  31080. }
  31081. pi = idx[p];
  31082. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31083. }
  31084. }
  31085. // normals
  31086. VertexData.ComputeNormals(positions, indices, normals);
  31087. if (closePath) {
  31088. var indexFirst = 0;
  31089. var indexLast = 0;
  31090. for (p = 0; p < pathArray.length; p++) {
  31091. indexFirst = idx[p] * 3;
  31092. if (p + 1 < pathArray.length) {
  31093. indexLast = (idx[p + 1] - 1) * 3;
  31094. }
  31095. else {
  31096. indexLast = normals.length - 3;
  31097. }
  31098. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31099. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31100. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31101. normals[indexLast] = normals[indexFirst];
  31102. normals[indexLast + 1] = normals[indexFirst + 1];
  31103. normals[indexLast + 2] = normals[indexFirst + 2];
  31104. }
  31105. }
  31106. // sides
  31107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31108. // Colors
  31109. var colors = null;
  31110. if (customColors) {
  31111. colors = new Float32Array(customColors.length * 4);
  31112. for (var c = 0; c < customColors.length; c++) {
  31113. colors[c * 4] = customColors[c].r;
  31114. colors[c * 4 + 1] = customColors[c].g;
  31115. colors[c * 4 + 2] = customColors[c].b;
  31116. colors[c * 4 + 3] = customColors[c].a;
  31117. }
  31118. }
  31119. // Result
  31120. var vertexData = new VertexData();
  31121. var positions32 = new Float32Array(positions);
  31122. var normals32 = new Float32Array(normals);
  31123. var uvs32 = new Float32Array(uvs);
  31124. vertexData.indices = indices;
  31125. vertexData.positions = positions32;
  31126. vertexData.normals = normals32;
  31127. vertexData.uvs = uvs32;
  31128. if (colors) {
  31129. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  31130. }
  31131. if (closePath) {
  31132. vertexData._idx = idx;
  31133. }
  31134. return vertexData;
  31135. };
  31136. /**
  31137. * Creates the VertexData of the Box.
  31138. */
  31139. VertexData.CreateBox = function (options) {
  31140. var normalsSource = [
  31141. new BABYLON.Vector3(0, 0, 1),
  31142. new BABYLON.Vector3(0, 0, -1),
  31143. new BABYLON.Vector3(1, 0, 0),
  31144. new BABYLON.Vector3(-1, 0, 0),
  31145. new BABYLON.Vector3(0, 1, 0),
  31146. new BABYLON.Vector3(0, -1, 0)
  31147. ];
  31148. var indices = [];
  31149. var positions = [];
  31150. var normals = [];
  31151. var uvs = [];
  31152. var width = options.width || options.size || 1;
  31153. var height = options.height || options.size || 1;
  31154. var depth = options.depth || options.size || 1;
  31155. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31156. var faceUV = options.faceUV || new Array(6);
  31157. var faceColors = options.faceColors;
  31158. var colors = [];
  31159. // default face colors and UV if undefined
  31160. for (var f = 0; f < 6; f++) {
  31161. if (faceUV[f] === undefined) {
  31162. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31163. }
  31164. if (faceColors && faceColors[f] === undefined) {
  31165. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31166. }
  31167. }
  31168. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31169. // Create each face in turn.
  31170. for (var index = 0; index < normalsSource.length; index++) {
  31171. var normal = normalsSource[index];
  31172. // Get two vectors perpendicular to the face normal and to each other.
  31173. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31174. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31175. // Six indices (two triangles) per face.
  31176. var verticesLength = positions.length / 3;
  31177. indices.push(verticesLength);
  31178. indices.push(verticesLength + 1);
  31179. indices.push(verticesLength + 2);
  31180. indices.push(verticesLength);
  31181. indices.push(verticesLength + 2);
  31182. indices.push(verticesLength + 3);
  31183. // Four vertices per face.
  31184. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31185. positions.push(vertex.x, vertex.y, vertex.z);
  31186. normals.push(normal.x, normal.y, normal.z);
  31187. uvs.push(faceUV[index].z, faceUV[index].w);
  31188. if (faceColors) {
  31189. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31190. }
  31191. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31192. positions.push(vertex.x, vertex.y, vertex.z);
  31193. normals.push(normal.x, normal.y, normal.z);
  31194. uvs.push(faceUV[index].x, faceUV[index].w);
  31195. if (faceColors) {
  31196. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31197. }
  31198. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31199. positions.push(vertex.x, vertex.y, vertex.z);
  31200. normals.push(normal.x, normal.y, normal.z);
  31201. uvs.push(faceUV[index].x, faceUV[index].y);
  31202. if (faceColors) {
  31203. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31204. }
  31205. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31206. positions.push(vertex.x, vertex.y, vertex.z);
  31207. normals.push(normal.x, normal.y, normal.z);
  31208. uvs.push(faceUV[index].z, faceUV[index].y);
  31209. if (faceColors) {
  31210. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31211. }
  31212. }
  31213. // sides
  31214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31215. // Result
  31216. var vertexData = new VertexData();
  31217. vertexData.indices = indices;
  31218. vertexData.positions = positions;
  31219. vertexData.normals = normals;
  31220. vertexData.uvs = uvs;
  31221. if (faceColors) {
  31222. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31223. vertexData.colors = totalColors;
  31224. }
  31225. return vertexData;
  31226. };
  31227. /**
  31228. * Creates the VertexData of the Sphere.
  31229. */
  31230. VertexData.CreateSphere = function (options) {
  31231. var segments = options.segments || 32;
  31232. var diameterX = options.diameterX || options.diameter || 1;
  31233. var diameterY = options.diameterY || options.diameter || 1;
  31234. var diameterZ = options.diameterZ || options.diameter || 1;
  31235. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31236. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31237. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31238. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31239. var totalZRotationSteps = 2 + segments;
  31240. var totalYRotationSteps = 2 * totalZRotationSteps;
  31241. var indices = [];
  31242. var positions = [];
  31243. var normals = [];
  31244. var uvs = [];
  31245. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31246. var normalizedZ = zRotationStep / totalZRotationSteps;
  31247. var angleZ = normalizedZ * Math.PI * slice;
  31248. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31249. var normalizedY = yRotationStep / totalYRotationSteps;
  31250. var angleY = normalizedY * Math.PI * 2 * arc;
  31251. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31252. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31253. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31254. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31255. var vertex = complete.multiply(radius);
  31256. var normal = complete.divide(radius).normalize();
  31257. positions.push(vertex.x, vertex.y, vertex.z);
  31258. normals.push(normal.x, normal.y, normal.z);
  31259. uvs.push(normalizedY, normalizedZ);
  31260. }
  31261. if (zRotationStep > 0) {
  31262. var verticesCount = positions.length / 3;
  31263. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31264. indices.push((firstIndex));
  31265. indices.push((firstIndex + 1));
  31266. indices.push(firstIndex + totalYRotationSteps + 1);
  31267. indices.push((firstIndex + totalYRotationSteps + 1));
  31268. indices.push((firstIndex + 1));
  31269. indices.push((firstIndex + totalYRotationSteps + 2));
  31270. }
  31271. }
  31272. }
  31273. // Sides
  31274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31275. // Result
  31276. var vertexData = new VertexData();
  31277. vertexData.indices = indices;
  31278. vertexData.positions = positions;
  31279. vertexData.normals = normals;
  31280. vertexData.uvs = uvs;
  31281. return vertexData;
  31282. };
  31283. /**
  31284. * Creates the VertexData of the Cylinder or Cone.
  31285. */
  31286. VertexData.CreateCylinder = function (options) {
  31287. var height = options.height || 2;
  31288. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31289. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31290. var tessellation = options.tessellation || 24;
  31291. var subdivisions = options.subdivisions || 1;
  31292. var hasRings = options.hasRings ? true : false;
  31293. var enclose = options.enclose ? true : false;
  31294. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31296. var faceUV = options.faceUV || new Array(3);
  31297. var faceColors = options.faceColors;
  31298. // default face colors and UV if undefined
  31299. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31300. var ringNb = (hasRings) ? subdivisions : 1;
  31301. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31302. var f;
  31303. for (f = 0; f < surfaceNb; f++) {
  31304. if (faceColors && faceColors[f] === undefined) {
  31305. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31306. }
  31307. }
  31308. for (f = 0; f < surfaceNb; f++) {
  31309. if (faceUV && faceUV[f] === undefined) {
  31310. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31311. }
  31312. }
  31313. var indices = new Array();
  31314. var positions = new Array();
  31315. var normals = new Array();
  31316. var uvs = new Array();
  31317. var colors = new Array();
  31318. var angle_step = Math.PI * 2 * arc / tessellation;
  31319. var angle;
  31320. var h;
  31321. var radius;
  31322. var tan = (diameterBottom - diameterTop) / 2 / height;
  31323. var ringVertex = BABYLON.Vector3.Zero();
  31324. var ringNormal = BABYLON.Vector3.Zero();
  31325. var ringFirstVertex = BABYLON.Vector3.Zero();
  31326. var ringFirstNormal = BABYLON.Vector3.Zero();
  31327. var quadNormal = BABYLON.Vector3.Zero();
  31328. var Y = BABYLON.Axis.Y;
  31329. // positions, normals, uvs
  31330. var i;
  31331. var j;
  31332. var r;
  31333. var ringIdx = 1;
  31334. var s = 1; // surface index
  31335. var cs = 0;
  31336. var v = 0;
  31337. for (i = 0; i <= subdivisions; i++) {
  31338. h = i / subdivisions;
  31339. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31340. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31341. for (r = 0; r < ringIdx; r++) {
  31342. if (hasRings) {
  31343. s += r;
  31344. }
  31345. if (enclose) {
  31346. s += 2 * r;
  31347. }
  31348. for (j = 0; j <= tessellation; j++) {
  31349. angle = j * angle_step;
  31350. // position
  31351. ringVertex.x = Math.cos(-angle) * radius;
  31352. ringVertex.y = -height / 2 + h * height;
  31353. ringVertex.z = Math.sin(-angle) * radius;
  31354. // normal
  31355. if (diameterTop === 0 && i === subdivisions) {
  31356. // if no top cap, reuse former normals
  31357. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31358. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31359. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31360. }
  31361. else {
  31362. ringNormal.x = ringVertex.x;
  31363. ringNormal.z = ringVertex.z;
  31364. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31365. ringNormal.normalize();
  31366. }
  31367. // keep first ring vertex values for enclose
  31368. if (j === 0) {
  31369. ringFirstVertex.copyFrom(ringVertex);
  31370. ringFirstNormal.copyFrom(ringNormal);
  31371. }
  31372. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31373. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31374. if (hasRings) {
  31375. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31376. }
  31377. else {
  31378. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31379. }
  31380. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31381. if (faceColors) {
  31382. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31383. }
  31384. }
  31385. // if enclose, add four vertices and their dedicated normals
  31386. if (arc !== 1 && enclose) {
  31387. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31388. positions.push(0, ringVertex.y, 0);
  31389. positions.push(0, ringVertex.y, 0);
  31390. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31391. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31392. quadNormal.normalize();
  31393. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31394. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31395. quadNormal.normalize();
  31396. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31397. if (hasRings) {
  31398. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31399. }
  31400. else {
  31401. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31402. }
  31403. uvs.push(faceUV[s + 1].x, v);
  31404. uvs.push(faceUV[s + 1].z, v);
  31405. if (hasRings) {
  31406. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31407. }
  31408. else {
  31409. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31410. }
  31411. uvs.push(faceUV[s + 2].x, v);
  31412. uvs.push(faceUV[s + 2].z, v);
  31413. if (faceColors) {
  31414. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31415. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31416. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31417. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31418. }
  31419. }
  31420. if (cs !== s) {
  31421. cs = s;
  31422. }
  31423. }
  31424. }
  31425. // indices
  31426. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31427. var s;
  31428. i = 0;
  31429. for (s = 0; s < subdivisions; s++) {
  31430. var i0 = 0;
  31431. var i1 = 0;
  31432. var i2 = 0;
  31433. var i3 = 0;
  31434. for (j = 0; j < tessellation; j++) {
  31435. i0 = i * (e + 1) + j;
  31436. i1 = (i + 1) * (e + 1) + j;
  31437. i2 = i * (e + 1) + (j + 1);
  31438. i3 = (i + 1) * (e + 1) + (j + 1);
  31439. indices.push(i0, i1, i2);
  31440. indices.push(i3, i2, i1);
  31441. }
  31442. if (arc !== 1 && enclose) {
  31443. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31444. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31445. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31446. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31447. }
  31448. i = (hasRings) ? (i + 2) : (i + 1);
  31449. }
  31450. // Caps
  31451. var createCylinderCap = function (isTop) {
  31452. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31453. if (radius === 0) {
  31454. return;
  31455. }
  31456. // Cap positions, normals & uvs
  31457. var angle;
  31458. var circleVector;
  31459. var i;
  31460. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31461. var c = null;
  31462. if (faceColors) {
  31463. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31464. }
  31465. // cap center
  31466. var vbase = positions.length / 3;
  31467. var offset = isTop ? height / 2 : -height / 2;
  31468. var center = new BABYLON.Vector3(0, offset, 0);
  31469. positions.push(center.x, center.y, center.z);
  31470. normals.push(0, isTop ? 1 : -1, 0);
  31471. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31472. if (c) {
  31473. colors.push(c.r, c.g, c.b, c.a);
  31474. }
  31475. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31476. for (i = 0; i <= tessellation; i++) {
  31477. angle = Math.PI * 2 * i * arc / tessellation;
  31478. var cos = Math.cos(-angle);
  31479. var sin = Math.sin(-angle);
  31480. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31481. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31482. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31483. normals.push(0, isTop ? 1 : -1, 0);
  31484. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31485. if (c) {
  31486. colors.push(c.r, c.g, c.b, c.a);
  31487. }
  31488. }
  31489. // Cap indices
  31490. for (i = 0; i < tessellation; i++) {
  31491. if (!isTop) {
  31492. indices.push(vbase);
  31493. indices.push(vbase + (i + 1));
  31494. indices.push(vbase + (i + 2));
  31495. }
  31496. else {
  31497. indices.push(vbase);
  31498. indices.push(vbase + (i + 2));
  31499. indices.push(vbase + (i + 1));
  31500. }
  31501. }
  31502. };
  31503. // add caps to geometry
  31504. createCylinderCap(false);
  31505. createCylinderCap(true);
  31506. // Sides
  31507. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31508. var vertexData = new VertexData();
  31509. vertexData.indices = indices;
  31510. vertexData.positions = positions;
  31511. vertexData.normals = normals;
  31512. vertexData.uvs = uvs;
  31513. if (faceColors) {
  31514. vertexData.colors = colors;
  31515. }
  31516. return vertexData;
  31517. };
  31518. /**
  31519. * Creates the VertexData of the Torus.
  31520. */
  31521. VertexData.CreateTorus = function (options) {
  31522. var indices = [];
  31523. var positions = [];
  31524. var normals = [];
  31525. var uvs = [];
  31526. var diameter = options.diameter || 1;
  31527. var thickness = options.thickness || 0.5;
  31528. var tessellation = options.tessellation || 16;
  31529. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31530. var stride = tessellation + 1;
  31531. for (var i = 0; i <= tessellation; i++) {
  31532. var u = i / tessellation;
  31533. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31534. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31535. for (var j = 0; j <= tessellation; j++) {
  31536. var v = 1 - j / tessellation;
  31537. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31538. var dx = Math.cos(innerAngle);
  31539. var dy = Math.sin(innerAngle);
  31540. // Create a vertex.
  31541. var normal = new BABYLON.Vector3(dx, dy, 0);
  31542. var position = normal.scale(thickness / 2);
  31543. var textureCoordinate = new BABYLON.Vector2(u, v);
  31544. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31545. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31546. positions.push(position.x, position.y, position.z);
  31547. normals.push(normal.x, normal.y, normal.z);
  31548. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31549. // And create indices for two triangles.
  31550. var nextI = (i + 1) % stride;
  31551. var nextJ = (j + 1) % stride;
  31552. indices.push(i * stride + j);
  31553. indices.push(i * stride + nextJ);
  31554. indices.push(nextI * stride + j);
  31555. indices.push(i * stride + nextJ);
  31556. indices.push(nextI * stride + nextJ);
  31557. indices.push(nextI * stride + j);
  31558. }
  31559. }
  31560. // Sides
  31561. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31562. // Result
  31563. var vertexData = new VertexData();
  31564. vertexData.indices = indices;
  31565. vertexData.positions = positions;
  31566. vertexData.normals = normals;
  31567. vertexData.uvs = uvs;
  31568. return vertexData;
  31569. };
  31570. /**
  31571. * Creates the VertexData of the LineSystem.
  31572. */
  31573. VertexData.CreateLineSystem = function (options) {
  31574. var indices = [];
  31575. var positions = [];
  31576. var lines = options.lines;
  31577. var colors = options.colors;
  31578. var vertexColors = [];
  31579. var idx = 0;
  31580. for (var l = 0; l < lines.length; l++) {
  31581. var points = lines[l];
  31582. for (var index = 0; index < points.length; index++) {
  31583. positions.push(points[index].x, points[index].y, points[index].z);
  31584. if (colors) {
  31585. var color = colors[l];
  31586. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31587. }
  31588. if (index > 0) {
  31589. indices.push(idx - 1);
  31590. indices.push(idx);
  31591. }
  31592. idx++;
  31593. }
  31594. }
  31595. var vertexData = new VertexData();
  31596. vertexData.indices = indices;
  31597. vertexData.positions = positions;
  31598. if (colors) {
  31599. vertexData.colors = vertexColors;
  31600. }
  31601. return vertexData;
  31602. };
  31603. /**
  31604. * Create the VertexData of the DashedLines.
  31605. */
  31606. VertexData.CreateDashedLines = function (options) {
  31607. var dashSize = options.dashSize || 3;
  31608. var gapSize = options.gapSize || 1;
  31609. var dashNb = options.dashNb || 200;
  31610. var points = options.points;
  31611. var positions = new Array();
  31612. var indices = new Array();
  31613. var curvect = BABYLON.Vector3.Zero();
  31614. var lg = 0;
  31615. var nb = 0;
  31616. var shft = 0;
  31617. var dashshft = 0;
  31618. var curshft = 0;
  31619. var idx = 0;
  31620. var i = 0;
  31621. for (i = 0; i < points.length - 1; i++) {
  31622. points[i + 1].subtractToRef(points[i], curvect);
  31623. lg += curvect.length();
  31624. }
  31625. shft = lg / dashNb;
  31626. dashshft = dashSize * shft / (dashSize + gapSize);
  31627. for (i = 0; i < points.length - 1; i++) {
  31628. points[i + 1].subtractToRef(points[i], curvect);
  31629. nb = Math.floor(curvect.length() / shft);
  31630. curvect.normalize();
  31631. for (var j = 0; j < nb; j++) {
  31632. curshft = shft * j;
  31633. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31634. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31635. indices.push(idx, idx + 1);
  31636. idx += 2;
  31637. }
  31638. }
  31639. // Result
  31640. var vertexData = new VertexData();
  31641. vertexData.positions = positions;
  31642. vertexData.indices = indices;
  31643. return vertexData;
  31644. };
  31645. /**
  31646. * Creates the VertexData of the Ground.
  31647. */
  31648. VertexData.CreateGround = function (options) {
  31649. var indices = [];
  31650. var positions = [];
  31651. var normals = [];
  31652. var uvs = [];
  31653. var row, col;
  31654. var width = options.width || 1;
  31655. var height = options.height || 1;
  31656. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31657. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31658. for (row = 0; row <= subdivisionsY; row++) {
  31659. for (col = 0; col <= subdivisionsX; col++) {
  31660. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31661. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31662. positions.push(position.x, position.y, position.z);
  31663. normals.push(normal.x, normal.y, normal.z);
  31664. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31665. }
  31666. }
  31667. for (row = 0; row < subdivisionsY; row++) {
  31668. for (col = 0; col < subdivisionsX; col++) {
  31669. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31670. indices.push(col + 1 + row * (subdivisionsX + 1));
  31671. indices.push(col + row * (subdivisionsX + 1));
  31672. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31673. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31674. indices.push(col + row * (subdivisionsX + 1));
  31675. }
  31676. }
  31677. // Result
  31678. var vertexData = new VertexData();
  31679. vertexData.indices = indices;
  31680. vertexData.positions = positions;
  31681. vertexData.normals = normals;
  31682. vertexData.uvs = uvs;
  31683. return vertexData;
  31684. };
  31685. /**
  31686. * Creates the VertexData of the TiledGround.
  31687. */
  31688. VertexData.CreateTiledGround = function (options) {
  31689. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31690. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31691. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31692. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31693. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31694. var precision = options.precision || { w: 1, h: 1 };
  31695. var indices = new Array();
  31696. var positions = new Array();
  31697. var normals = new Array();
  31698. var uvs = new Array();
  31699. var row, col, tileRow, tileCol;
  31700. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31701. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31702. precision.w = (precision.w < 1) ? 1 : precision.w;
  31703. precision.h = (precision.h < 1) ? 1 : precision.h;
  31704. var tileSize = {
  31705. 'w': (xmax - xmin) / subdivisions.w,
  31706. 'h': (zmax - zmin) / subdivisions.h
  31707. };
  31708. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31709. // Indices
  31710. var base = positions.length / 3;
  31711. var rowLength = precision.w + 1;
  31712. for (row = 0; row < precision.h; row++) {
  31713. for (col = 0; col < precision.w; col++) {
  31714. var square = [
  31715. base + col + row * rowLength,
  31716. base + (col + 1) + row * rowLength,
  31717. base + (col + 1) + (row + 1) * rowLength,
  31718. base + col + (row + 1) * rowLength
  31719. ];
  31720. indices.push(square[1]);
  31721. indices.push(square[2]);
  31722. indices.push(square[3]);
  31723. indices.push(square[0]);
  31724. indices.push(square[1]);
  31725. indices.push(square[3]);
  31726. }
  31727. }
  31728. // Position, normals and uvs
  31729. var position = BABYLON.Vector3.Zero();
  31730. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31731. for (row = 0; row <= precision.h; row++) {
  31732. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31733. for (col = 0; col <= precision.w; col++) {
  31734. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31735. position.y = 0;
  31736. positions.push(position.x, position.y, position.z);
  31737. normals.push(normal.x, normal.y, normal.z);
  31738. uvs.push(col / precision.w, row / precision.h);
  31739. }
  31740. }
  31741. }
  31742. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31743. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31744. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31745. }
  31746. }
  31747. // Result
  31748. var vertexData = new VertexData();
  31749. vertexData.indices = indices;
  31750. vertexData.positions = positions;
  31751. vertexData.normals = normals;
  31752. vertexData.uvs = uvs;
  31753. return vertexData;
  31754. };
  31755. /**
  31756. * Creates the VertexData of the Ground designed from a heightmap.
  31757. */
  31758. VertexData.CreateGroundFromHeightMap = function (options) {
  31759. var indices = [];
  31760. var positions = [];
  31761. var normals = [];
  31762. var uvs = [];
  31763. var row, col;
  31764. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31765. // Vertices
  31766. for (row = 0; row <= options.subdivisions; row++) {
  31767. for (col = 0; col <= options.subdivisions; col++) {
  31768. 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));
  31769. // Compute height
  31770. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31771. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31772. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31773. var r = options.buffer[pos] / 255.0;
  31774. var g = options.buffer[pos + 1] / 255.0;
  31775. var b = options.buffer[pos + 2] / 255.0;
  31776. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31777. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31778. // Add vertex
  31779. positions.push(position.x, position.y, position.z);
  31780. normals.push(0, 0, 0);
  31781. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31782. }
  31783. }
  31784. // Indices
  31785. for (row = 0; row < options.subdivisions; row++) {
  31786. for (col = 0; col < options.subdivisions; col++) {
  31787. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31788. indices.push(col + 1 + row * (options.subdivisions + 1));
  31789. indices.push(col + row * (options.subdivisions + 1));
  31790. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31791. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31792. indices.push(col + row * (options.subdivisions + 1));
  31793. }
  31794. }
  31795. // Normals
  31796. VertexData.ComputeNormals(positions, indices, normals);
  31797. // Result
  31798. var vertexData = new VertexData();
  31799. vertexData.indices = indices;
  31800. vertexData.positions = positions;
  31801. vertexData.normals = normals;
  31802. vertexData.uvs = uvs;
  31803. return vertexData;
  31804. };
  31805. /**
  31806. * Creates the VertexData of the Plane.
  31807. */
  31808. VertexData.CreatePlane = function (options) {
  31809. var indices = [];
  31810. var positions = [];
  31811. var normals = [];
  31812. var uvs = [];
  31813. var width = options.width || options.size || 1;
  31814. var height = options.height || options.size || 1;
  31815. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31816. // Vertices
  31817. var halfWidth = width / 2.0;
  31818. var halfHeight = height / 2.0;
  31819. positions.push(-halfWidth, -halfHeight, 0);
  31820. normals.push(0, 0, -1.0);
  31821. uvs.push(0.0, 0.0);
  31822. positions.push(halfWidth, -halfHeight, 0);
  31823. normals.push(0, 0, -1.0);
  31824. uvs.push(1.0, 0.0);
  31825. positions.push(halfWidth, halfHeight, 0);
  31826. normals.push(0, 0, -1.0);
  31827. uvs.push(1.0, 1.0);
  31828. positions.push(-halfWidth, halfHeight, 0);
  31829. normals.push(0, 0, -1.0);
  31830. uvs.push(0.0, 1.0);
  31831. // Indices
  31832. indices.push(0);
  31833. indices.push(1);
  31834. indices.push(2);
  31835. indices.push(0);
  31836. indices.push(2);
  31837. indices.push(3);
  31838. // Sides
  31839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31840. // Result
  31841. var vertexData = new VertexData();
  31842. vertexData.indices = indices;
  31843. vertexData.positions = positions;
  31844. vertexData.normals = normals;
  31845. vertexData.uvs = uvs;
  31846. return vertexData;
  31847. };
  31848. /**
  31849. * Creates the VertexData of the Disc or regular Polygon.
  31850. */
  31851. VertexData.CreateDisc = function (options) {
  31852. var positions = new Array();
  31853. var indices = new Array();
  31854. var normals = new Array();
  31855. var uvs = new Array();
  31856. var radius = options.radius || 0.5;
  31857. var tessellation = options.tessellation || 64;
  31858. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31859. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31860. // positions and uvs
  31861. positions.push(0, 0, 0); // disc center first
  31862. uvs.push(0.5, 0.5);
  31863. var theta = Math.PI * 2 * arc;
  31864. var step = theta / tessellation;
  31865. for (var a = 0; a < theta; a += step) {
  31866. var x = Math.cos(a);
  31867. var y = Math.sin(a);
  31868. var u = (x + 1) / 2;
  31869. var v = (1 - y) / 2;
  31870. positions.push(radius * x, radius * y, 0);
  31871. uvs.push(u, v);
  31872. }
  31873. if (arc === 1) {
  31874. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31875. uvs.push(uvs[2], uvs[3]);
  31876. }
  31877. //indices
  31878. var vertexNb = positions.length / 3;
  31879. for (var i = 1; i < vertexNb - 1; i++) {
  31880. indices.push(i + 1, 0, i);
  31881. }
  31882. // result
  31883. VertexData.ComputeNormals(positions, indices, normals);
  31884. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31885. var vertexData = new VertexData();
  31886. vertexData.indices = indices;
  31887. vertexData.positions = positions;
  31888. vertexData.normals = normals;
  31889. vertexData.uvs = uvs;
  31890. return vertexData;
  31891. };
  31892. /**
  31893. * Re-creates the VertexData of the Polygon for sideOrientation.
  31894. */
  31895. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31896. var faceUV = fUV || new Array(3);
  31897. var faceColors = fColors;
  31898. var colors = [];
  31899. // default face colors and UV if undefined
  31900. for (var f = 0; f < 3; f++) {
  31901. if (faceUV[f] === undefined) {
  31902. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31903. }
  31904. if (faceColors && faceColors[f] === undefined) {
  31905. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31906. }
  31907. }
  31908. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31909. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31910. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31911. var indices = polygon.getIndices();
  31912. // set face colours and textures
  31913. var idx = 0;
  31914. var face = 0;
  31915. for (var index = 0; index < normals.length; index += 3) {
  31916. //Edge Face no. 1
  31917. if (Math.abs(normals[index + 1]) < 0.001) {
  31918. face = 1;
  31919. }
  31920. //Top Face no. 0
  31921. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31922. face = 0;
  31923. }
  31924. //Bottom Face no. 2
  31925. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31926. face = 2;
  31927. }
  31928. idx = index / 3;
  31929. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31930. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31931. if (faceColors) {
  31932. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31933. }
  31934. }
  31935. // sides
  31936. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31937. // Result
  31938. var vertexData = new VertexData();
  31939. vertexData.indices = indices;
  31940. vertexData.positions = positions;
  31941. vertexData.normals = normals;
  31942. vertexData.uvs = uvs;
  31943. if (faceColors) {
  31944. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31945. vertexData.colors = totalColors;
  31946. }
  31947. return vertexData;
  31948. };
  31949. /**
  31950. * Creates the VertexData of the IcoSphere.
  31951. */
  31952. VertexData.CreateIcoSphere = function (options) {
  31953. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31954. var radius = options.radius || 1;
  31955. var flat = (options.flat === undefined) ? true : options.flat;
  31956. var subdivisions = options.subdivisions || 4;
  31957. var radiusX = options.radiusX || radius;
  31958. var radiusY = options.radiusY || radius;
  31959. var radiusZ = options.radiusZ || radius;
  31960. var t = (1 + Math.sqrt(5)) / 2;
  31961. // 12 vertex x,y,z
  31962. var ico_vertices = [
  31963. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31964. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31965. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31966. ];
  31967. // index of 3 vertex makes a face of icopshere
  31968. var ico_indices = [
  31969. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31970. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31971. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31972. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31973. ];
  31974. // vertex for uv have aliased position, not for UV
  31975. var vertices_unalias_id = [
  31976. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31977. // vertex alias
  31978. 0,
  31979. 2,
  31980. 3,
  31981. 3,
  31982. 3,
  31983. 4,
  31984. 7,
  31985. 8,
  31986. 9,
  31987. 9,
  31988. 10,
  31989. 11 // 23: B + 12
  31990. ];
  31991. // uv as integer step (not pixels !)
  31992. var ico_vertexuv = [
  31993. 5, 1, 3, 1, 6, 4, 0, 0,
  31994. 5, 3, 4, 2, 2, 2, 4, 0,
  31995. 2, 0, 1, 1, 6, 0, 6, 2,
  31996. // vertex alias (for same vertex on different faces)
  31997. 0, 4,
  31998. 3, 3,
  31999. 4, 4,
  32000. 3, 1,
  32001. 4, 2,
  32002. 4, 4,
  32003. 0, 2,
  32004. 1, 1,
  32005. 2, 2,
  32006. 3, 3,
  32007. 1, 3,
  32008. 2, 4 // 23: B + 12
  32009. ];
  32010. // Vertices[0, 1, ...9, A, B] : position on UV plane
  32011. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  32012. // First island of uv mapping
  32013. // v = 4h 3+ 2
  32014. // v = 3h 9+ 4
  32015. // v = 2h 9+ 5 B
  32016. // v = 1h 9 1 0
  32017. // v = 0h 3 8 7 A
  32018. // u = 0 1 2 3 4 5 6 *a
  32019. // Second island of uv mapping
  32020. // v = 4h 0+ B+ 4+
  32021. // v = 3h A+ 2+
  32022. // v = 2h 7+ 6 3+
  32023. // v = 1h 8+ 3+
  32024. // v = 0h
  32025. // u = 0 1 2 3 4 5 6 *a
  32026. // Face layout on texture UV mapping
  32027. // ============
  32028. // \ 4 /\ 16 / ======
  32029. // \ / \ / /\ 11 /
  32030. // \/ 7 \/ / \ /
  32031. // ======= / 10 \/
  32032. // /\ 17 /\ =======
  32033. // / \ / \ \ 15 /\
  32034. // / 8 \/ 12 \ \ / \
  32035. // ============ \/ 6 \
  32036. // \ 18 /\ ============
  32037. // \ / \ \ 5 /\ 0 /
  32038. // \/ 13 \ \ / \ /
  32039. // ======= \/ 1 \/
  32040. // =============
  32041. // /\ 19 /\ 2 /\
  32042. // / \ / \ / \
  32043. // / 14 \/ 9 \/ 3 \
  32044. // ===================
  32045. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32046. var ustep = 138 / 1024;
  32047. var vstep = 239 / 1024;
  32048. var uoffset = 60 / 1024;
  32049. var voffset = 26 / 1024;
  32050. // Second island should have margin, not to touch the first island
  32051. // avoid any borderline artefact in pixel rounding
  32052. var island_u_offset = -40 / 1024;
  32053. var island_v_offset = +20 / 1024;
  32054. // face is either island 0 or 1 :
  32055. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32056. var island = [
  32057. 0, 0, 0, 0, 1,
  32058. 0, 0, 1, 1, 0,
  32059. 0, 0, 1, 1, 0,
  32060. 0, 1, 1, 1, 0 // 15 - 19
  32061. ];
  32062. var indices = new Array();
  32063. var positions = new Array();
  32064. var normals = new Array();
  32065. var uvs = new Array();
  32066. var current_indice = 0;
  32067. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32068. var face_vertex_pos = new Array(3);
  32069. var face_vertex_uv = new Array(3);
  32070. var v012;
  32071. for (v012 = 0; v012 < 3; v012++) {
  32072. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32073. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32074. }
  32075. // create all with normals
  32076. for (var face = 0; face < 20; face++) {
  32077. // 3 vertex per face
  32078. for (v012 = 0; v012 < 3; v012++) {
  32079. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32080. var v_id = ico_indices[3 * face + v012];
  32081. // vertex have 3D position (x,y,z)
  32082. 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]);
  32083. // Normalize to get normal, then scale to radius
  32084. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32085. // uv Coordinates from vertex ID
  32086. 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);
  32087. }
  32088. // Subdivide the face (interpolate pos, norm, uv)
  32089. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32090. // - norm is linear interpolation of vertex corner normal
  32091. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32092. // - uv is linear interpolation
  32093. //
  32094. // Topology is as below for sub-divide by 2
  32095. // vertex shown as v0,v1,v2
  32096. // interp index is i1 to progress in range [v0,v1[
  32097. // interp index is i2 to progress in range [v0,v2[
  32098. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32099. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32100. //
  32101. //
  32102. // i2 v2
  32103. // ^ ^
  32104. // / / \
  32105. // / / \
  32106. // / / \
  32107. // / / (0,1) \
  32108. // / #---------\
  32109. // / / \ (0,0)'/ \
  32110. // / / \ / \
  32111. // / / \ / \
  32112. // / / (0,0) \ / (1,0) \
  32113. // / #---------#---------\
  32114. // v0 v1
  32115. //
  32116. // --------------------> i1
  32117. //
  32118. // interp of (i1,i2):
  32119. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32120. // along i1 : lerp(x0,x1, i1/(S-i2))
  32121. //
  32122. // centroid of triangle is needed to get help normal computation
  32123. // (c1,c2) are used for centroid location
  32124. var interp_vertex = function (i1, i2, c1, c2) {
  32125. // vertex is interpolated from
  32126. // - face_vertex_pos[0..2]
  32127. // - face_vertex_uv[0..2]
  32128. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32129. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32130. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32131. pos_interp.normalize();
  32132. var vertex_normal;
  32133. if (flat) {
  32134. // in flat mode, recalculate normal as face centroid normal
  32135. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32136. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32137. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32138. }
  32139. else {
  32140. // in smooth mode, recalculate normal from each single vertex position
  32141. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32142. }
  32143. // Vertex normal need correction due to X,Y,Z radius scaling
  32144. vertex_normal.x /= radiusX;
  32145. vertex_normal.y /= radiusY;
  32146. vertex_normal.z /= radiusZ;
  32147. vertex_normal.normalize();
  32148. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32149. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32150. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32151. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32152. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32153. uvs.push(uv_interp.x, uv_interp.y);
  32154. // push each vertex has member of a face
  32155. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32156. indices.push(current_indice);
  32157. current_indice++;
  32158. };
  32159. for (var i2 = 0; i2 < subdivisions; i2++) {
  32160. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32161. // face : (i1,i2) for /\ :
  32162. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32163. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32164. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32165. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32166. if (i1 + i2 + 1 < subdivisions) {
  32167. // face : (i1,i2)' for \/ :
  32168. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32169. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32170. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32171. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32172. }
  32173. }
  32174. }
  32175. }
  32176. // Sides
  32177. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32178. // Result
  32179. var vertexData = new VertexData();
  32180. vertexData.indices = indices;
  32181. vertexData.positions = positions;
  32182. vertexData.normals = normals;
  32183. vertexData.uvs = uvs;
  32184. return vertexData;
  32185. };
  32186. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32187. /**
  32188. * Creates the VertexData of the Polyhedron.
  32189. */
  32190. VertexData.CreatePolyhedron = function (options) {
  32191. // provided polyhedron types :
  32192. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32193. // 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)
  32194. var polyhedra = [];
  32195. 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]] };
  32196. 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]] };
  32197. polyhedra[2] = {
  32198. 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]],
  32199. 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]]
  32200. };
  32201. polyhedra[3] = {
  32202. 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]],
  32203. 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]]
  32204. };
  32205. polyhedra[4] = {
  32206. 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]],
  32207. 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]]
  32208. };
  32209. 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]] };
  32210. 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]] };
  32211. 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]] };
  32212. 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]] };
  32213. 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]] };
  32214. 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]] };
  32215. 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]] };
  32216. 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]] };
  32217. 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]] };
  32218. polyhedra[14] = {
  32219. 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]],
  32220. 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]]
  32221. };
  32222. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32223. var size = options.size;
  32224. var sizeX = options.sizeX || size || 1;
  32225. var sizeY = options.sizeY || size || 1;
  32226. var sizeZ = options.sizeZ || size || 1;
  32227. var data = options.custom || polyhedra[type];
  32228. var nbfaces = data.face.length;
  32229. var faceUV = options.faceUV || new Array(nbfaces);
  32230. var faceColors = options.faceColors;
  32231. var flat = (options.flat === undefined) ? true : options.flat;
  32232. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32233. var positions = new Array();
  32234. var indices = new Array();
  32235. var normals = new Array();
  32236. var uvs = new Array();
  32237. var colors = new Array();
  32238. var index = 0;
  32239. var faceIdx = 0; // face cursor in the array "indexes"
  32240. var indexes = new Array();
  32241. var i = 0;
  32242. var f = 0;
  32243. var u, v, ang, x, y, tmp;
  32244. // default face colors and UV if undefined
  32245. if (flat) {
  32246. for (f = 0; f < nbfaces; f++) {
  32247. if (faceColors && faceColors[f] === undefined) {
  32248. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32249. }
  32250. if (faceUV && faceUV[f] === undefined) {
  32251. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32252. }
  32253. }
  32254. }
  32255. if (!flat) {
  32256. for (i = 0; i < data.vertex.length; i++) {
  32257. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32258. uvs.push(0, 0);
  32259. }
  32260. for (f = 0; f < nbfaces; f++) {
  32261. for (i = 0; i < data.face[f].length - 2; i++) {
  32262. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32263. }
  32264. }
  32265. }
  32266. else {
  32267. for (f = 0; f < nbfaces; f++) {
  32268. var fl = data.face[f].length; // number of vertices of the current face
  32269. ang = 2 * Math.PI / fl;
  32270. x = 0.5 * Math.tan(ang / 2);
  32271. y = 0.5;
  32272. // positions, uvs, colors
  32273. for (i = 0; i < fl; i++) {
  32274. // positions
  32275. 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);
  32276. indexes.push(index);
  32277. index++;
  32278. // uvs
  32279. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32280. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32281. uvs.push(u, v);
  32282. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32283. y = x * Math.sin(ang) + y * Math.cos(ang);
  32284. x = tmp;
  32285. // colors
  32286. if (faceColors) {
  32287. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32288. }
  32289. }
  32290. // indices from indexes
  32291. for (i = 0; i < fl - 2; i++) {
  32292. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32293. }
  32294. faceIdx += fl;
  32295. }
  32296. }
  32297. VertexData.ComputeNormals(positions, indices, normals);
  32298. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32299. var vertexData = new VertexData();
  32300. vertexData.positions = positions;
  32301. vertexData.indices = indices;
  32302. vertexData.normals = normals;
  32303. vertexData.uvs = uvs;
  32304. if (faceColors && flat) {
  32305. vertexData.colors = colors;
  32306. }
  32307. return vertexData;
  32308. };
  32309. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32310. /**
  32311. * Creates the VertexData of the Torus Knot.
  32312. */
  32313. VertexData.CreateTorusKnot = function (options) {
  32314. var indices = new Array();
  32315. var positions = new Array();
  32316. var normals = new Array();
  32317. var uvs = new Array();
  32318. var radius = options.radius || 2;
  32319. var tube = options.tube || 0.5;
  32320. var radialSegments = options.radialSegments || 32;
  32321. var tubularSegments = options.tubularSegments || 32;
  32322. var p = options.p || 2;
  32323. var q = options.q || 3;
  32324. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32325. // Helper
  32326. var getPos = function (angle) {
  32327. var cu = Math.cos(angle);
  32328. var su = Math.sin(angle);
  32329. var quOverP = q / p * angle;
  32330. var cs = Math.cos(quOverP);
  32331. var tx = radius * (2 + cs) * 0.5 * cu;
  32332. var ty = radius * (2 + cs) * su * 0.5;
  32333. var tz = radius * Math.sin(quOverP) * 0.5;
  32334. return new BABYLON.Vector3(tx, ty, tz);
  32335. };
  32336. // Vertices
  32337. var i;
  32338. var j;
  32339. for (i = 0; i <= radialSegments; i++) {
  32340. var modI = i % radialSegments;
  32341. var u = modI / radialSegments * 2 * p * Math.PI;
  32342. var p1 = getPos(u);
  32343. var p2 = getPos(u + 0.01);
  32344. var tang = p2.subtract(p1);
  32345. var n = p2.add(p1);
  32346. var bitan = BABYLON.Vector3.Cross(tang, n);
  32347. n = BABYLON.Vector3.Cross(bitan, tang);
  32348. bitan.normalize();
  32349. n.normalize();
  32350. for (j = 0; j < tubularSegments; j++) {
  32351. var modJ = j % tubularSegments;
  32352. var v = modJ / tubularSegments * 2 * Math.PI;
  32353. var cx = -tube * Math.cos(v);
  32354. var cy = tube * Math.sin(v);
  32355. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32356. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32357. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32358. uvs.push(i / radialSegments);
  32359. uvs.push(j / tubularSegments);
  32360. }
  32361. }
  32362. for (i = 0; i < radialSegments; i++) {
  32363. for (j = 0; j < tubularSegments; j++) {
  32364. var jNext = (j + 1) % tubularSegments;
  32365. var a = i * tubularSegments + j;
  32366. var b = (i + 1) * tubularSegments + j;
  32367. var c = (i + 1) * tubularSegments + jNext;
  32368. var d = i * tubularSegments + jNext;
  32369. indices.push(d);
  32370. indices.push(b);
  32371. indices.push(a);
  32372. indices.push(d);
  32373. indices.push(c);
  32374. indices.push(b);
  32375. }
  32376. }
  32377. // Normals
  32378. VertexData.ComputeNormals(positions, indices, normals);
  32379. // Sides
  32380. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32381. // Result
  32382. var vertexData = new VertexData();
  32383. vertexData.indices = indices;
  32384. vertexData.positions = positions;
  32385. vertexData.normals = normals;
  32386. vertexData.uvs = uvs;
  32387. return vertexData;
  32388. };
  32389. // Tools
  32390. /**
  32391. * @param {any} - positions (number[] or Float32Array)
  32392. * @param {any} - indices (number[] or Uint16Array)
  32393. * @param {any} - normals (number[] or Float32Array)
  32394. * options (optional) :
  32395. * facetPositions : optional array of facet positions (vector3)
  32396. * facetNormals : optional array of facet normals (vector3)
  32397. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32398. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32399. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32400. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32401. * bInfo : optional bounding info, required for facetPartitioning computation
  32402. * useRightHandedSystem: optional boolean to for right handed system computation
  32403. * depthSort : optional boolean to enable the facet depth sort computation
  32404. * distanceTo : optional Vector3 to compute the facet depth from this location
  32405. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32406. */
  32407. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32408. // temporary scalar variables
  32409. var index = 0; // facet index
  32410. var p1p2x = 0.0; // p1p2 vector x coordinate
  32411. var p1p2y = 0.0; // p1p2 vector y coordinate
  32412. var p1p2z = 0.0; // p1p2 vector z coordinate
  32413. var p3p2x = 0.0; // p3p2 vector x coordinate
  32414. var p3p2y = 0.0; // p3p2 vector y coordinate
  32415. var p3p2z = 0.0; // p3p2 vector z coordinate
  32416. var faceNormalx = 0.0; // facet normal x coordinate
  32417. var faceNormaly = 0.0; // facet normal y coordinate
  32418. var faceNormalz = 0.0; // facet normal z coordinate
  32419. var length = 0.0; // facet normal length before normalization
  32420. var v1x = 0; // vector1 x index in the positions array
  32421. var v1y = 0; // vector1 y index in the positions array
  32422. var v1z = 0; // vector1 z index in the positions array
  32423. var v2x = 0; // vector2 x index in the positions array
  32424. var v2y = 0; // vector2 y index in the positions array
  32425. var v2z = 0; // vector2 z index in the positions array
  32426. var v3x = 0; // vector3 x index in the positions array
  32427. var v3y = 0; // vector3 y index in the positions array
  32428. var v3z = 0; // vector3 z index in the positions array
  32429. var computeFacetNormals = false;
  32430. var computeFacetPositions = false;
  32431. var computeFacetPartitioning = false;
  32432. var computeDepthSort = false;
  32433. var faceNormalSign = 1;
  32434. var ratio = 0;
  32435. var distanceTo = null;
  32436. if (options) {
  32437. computeFacetNormals = (options.facetNormals) ? true : false;
  32438. computeFacetPositions = (options.facetPositions) ? true : false;
  32439. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32440. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32441. ratio = options.ratio || 0;
  32442. computeDepthSort = (options.depthSort) ? true : false;
  32443. distanceTo = (options.distanceTo);
  32444. if (computeDepthSort) {
  32445. if (distanceTo === undefined) {
  32446. distanceTo = BABYLON.Vector3.Zero();
  32447. }
  32448. var depthSortedFacets = options.depthSortedFacets;
  32449. }
  32450. }
  32451. // facetPartitioning reinit if needed
  32452. var xSubRatio = 0;
  32453. var ySubRatio = 0;
  32454. var zSubRatio = 0;
  32455. var subSq = 0;
  32456. if (computeFacetPartitioning && options && options.bbSize) {
  32457. var ox = 0; // X partitioning index for facet position
  32458. var oy = 0; // Y partinioning index for facet position
  32459. var oz = 0; // Z partinioning index for facet position
  32460. var b1x = 0; // X partitioning index for facet v1 vertex
  32461. var b1y = 0; // Y partitioning index for facet v1 vertex
  32462. var b1z = 0; // z partitioning index for facet v1 vertex
  32463. var b2x = 0; // X partitioning index for facet v2 vertex
  32464. var b2y = 0; // Y partitioning index for facet v2 vertex
  32465. var b2z = 0; // Z partitioning index for facet v2 vertex
  32466. var b3x = 0; // X partitioning index for facet v3 vertex
  32467. var b3y = 0; // Y partitioning index for facet v3 vertex
  32468. var b3z = 0; // Z partitioning index for facet v3 vertex
  32469. var block_idx_o = 0; // facet barycenter block index
  32470. var block_idx_v1 = 0; // v1 vertex block index
  32471. var block_idx_v2 = 0; // v2 vertex block index
  32472. var block_idx_v3 = 0; // v3 vertex block index
  32473. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32474. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32475. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32476. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32477. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32478. subSq = options.subDiv.max * options.subDiv.max;
  32479. options.facetPartitioning.length = 0;
  32480. }
  32481. // reset the normals
  32482. for (index = 0; index < positions.length; index++) {
  32483. normals[index] = 0.0;
  32484. }
  32485. // Loop : 1 indice triplet = 1 facet
  32486. var nbFaces = (indices.length / 3) | 0;
  32487. for (index = 0; index < nbFaces; index++) {
  32488. // get the indexes of the coordinates of each vertex of the facet
  32489. v1x = indices[index * 3] * 3;
  32490. v1y = v1x + 1;
  32491. v1z = v1x + 2;
  32492. v2x = indices[index * 3 + 1] * 3;
  32493. v2y = v2x + 1;
  32494. v2z = v2x + 2;
  32495. v3x = indices[index * 3 + 2] * 3;
  32496. v3y = v3x + 1;
  32497. v3z = v3x + 2;
  32498. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32499. p1p2y = positions[v1y] - positions[v2y];
  32500. p1p2z = positions[v1z] - positions[v2z];
  32501. p3p2x = positions[v3x] - positions[v2x];
  32502. p3p2y = positions[v3y] - positions[v2y];
  32503. p3p2z = positions[v3z] - positions[v2z];
  32504. // compute the face normal with the cross product
  32505. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32506. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32507. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32508. // normalize this normal and store it in the array facetData
  32509. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32510. length = (length === 0) ? 1.0 : length;
  32511. faceNormalx /= length;
  32512. faceNormaly /= length;
  32513. faceNormalz /= length;
  32514. if (computeFacetNormals && options) {
  32515. options.facetNormals[index].x = faceNormalx;
  32516. options.facetNormals[index].y = faceNormaly;
  32517. options.facetNormals[index].z = faceNormalz;
  32518. }
  32519. if (computeFacetPositions && options) {
  32520. // compute and the facet barycenter coordinates in the array facetPositions
  32521. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32522. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32523. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32524. }
  32525. if (computeFacetPartitioning && options) {
  32526. // store the facet indexes in arrays in the main facetPartitioning array :
  32527. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32528. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32529. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32530. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32531. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32532. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32533. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32534. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32535. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32536. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32537. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32538. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32539. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32540. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32541. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32542. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32543. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32544. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32545. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32546. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32547. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32548. // push each facet index in each block containing the vertex
  32549. options.facetPartitioning[block_idx_v1].push(index);
  32550. if (block_idx_v2 != block_idx_v1) {
  32551. options.facetPartitioning[block_idx_v2].push(index);
  32552. }
  32553. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32554. options.facetPartitioning[block_idx_v3].push(index);
  32555. }
  32556. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32557. options.facetPartitioning[block_idx_o].push(index);
  32558. }
  32559. }
  32560. if (computeDepthSort && options && options.facetPositions) {
  32561. var dsf = depthSortedFacets[index];
  32562. dsf.ind = index * 3;
  32563. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32564. }
  32565. // compute the normals anyway
  32566. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32567. normals[v1y] += faceNormaly;
  32568. normals[v1z] += faceNormalz;
  32569. normals[v2x] += faceNormalx;
  32570. normals[v2y] += faceNormaly;
  32571. normals[v2z] += faceNormalz;
  32572. normals[v3x] += faceNormalx;
  32573. normals[v3y] += faceNormaly;
  32574. normals[v3z] += faceNormalz;
  32575. }
  32576. // last normalization of each normal
  32577. for (index = 0; index < normals.length / 3; index++) {
  32578. faceNormalx = normals[index * 3];
  32579. faceNormaly = normals[index * 3 + 1];
  32580. faceNormalz = normals[index * 3 + 2];
  32581. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32582. length = (length === 0) ? 1.0 : length;
  32583. faceNormalx /= length;
  32584. faceNormaly /= length;
  32585. faceNormalz /= length;
  32586. normals[index * 3] = faceNormalx;
  32587. normals[index * 3 + 1] = faceNormaly;
  32588. normals[index * 3 + 2] = faceNormalz;
  32589. }
  32590. };
  32591. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32592. var li = indices.length;
  32593. var ln = normals.length;
  32594. var i;
  32595. var n;
  32596. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32597. switch (sideOrientation) {
  32598. case BABYLON.Mesh.FRONTSIDE:
  32599. // nothing changed
  32600. break;
  32601. case BABYLON.Mesh.BACKSIDE:
  32602. var tmp;
  32603. // indices
  32604. for (i = 0; i < li; i += 3) {
  32605. tmp = indices[i];
  32606. indices[i] = indices[i + 2];
  32607. indices[i + 2] = tmp;
  32608. }
  32609. // normals
  32610. for (n = 0; n < ln; n++) {
  32611. normals[n] = -normals[n];
  32612. }
  32613. break;
  32614. case BABYLON.Mesh.DOUBLESIDE:
  32615. // positions
  32616. var lp = positions.length;
  32617. var l = lp / 3;
  32618. for (var p = 0; p < lp; p++) {
  32619. positions[lp + p] = positions[p];
  32620. }
  32621. // indices
  32622. for (i = 0; i < li; i += 3) {
  32623. indices[i + li] = indices[i + 2] + l;
  32624. indices[i + 1 + li] = indices[i + 1] + l;
  32625. indices[i + 2 + li] = indices[i] + l;
  32626. }
  32627. // normals
  32628. for (n = 0; n < ln; n++) {
  32629. normals[ln + n] = -normals[n];
  32630. }
  32631. // uvs
  32632. var lu = uvs.length;
  32633. var u = 0;
  32634. for (u = 0; u < lu; u++) {
  32635. uvs[u + lu] = uvs[u];
  32636. }
  32637. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32638. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32639. u = 0;
  32640. for (i = 0; i < lu / 2; i++) {
  32641. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32642. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32643. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32644. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32645. u += 2;
  32646. }
  32647. break;
  32648. }
  32649. };
  32650. /**
  32651. * Creates a new VertexData from the imported parameters.
  32652. */
  32653. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32654. var vertexData = new VertexData();
  32655. // positions
  32656. var positions = parsedVertexData.positions;
  32657. if (positions) {
  32658. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32659. }
  32660. // normals
  32661. var normals = parsedVertexData.normals;
  32662. if (normals) {
  32663. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32664. }
  32665. // tangents
  32666. var tangents = parsedVertexData.tangents;
  32667. if (tangents) {
  32668. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32669. }
  32670. // uvs
  32671. var uvs = parsedVertexData.uvs;
  32672. if (uvs) {
  32673. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32674. }
  32675. // uv2s
  32676. var uv2s = parsedVertexData.uv2s;
  32677. if (uv2s) {
  32678. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32679. }
  32680. // uv3s
  32681. var uv3s = parsedVertexData.uv3s;
  32682. if (uv3s) {
  32683. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32684. }
  32685. // uv4s
  32686. var uv4s = parsedVertexData.uv4s;
  32687. if (uv4s) {
  32688. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32689. }
  32690. // uv5s
  32691. var uv5s = parsedVertexData.uv5s;
  32692. if (uv5s) {
  32693. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32694. }
  32695. // uv6s
  32696. var uv6s = parsedVertexData.uv6s;
  32697. if (uv6s) {
  32698. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32699. }
  32700. // colors
  32701. var colors = parsedVertexData.colors;
  32702. if (colors) {
  32703. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32704. }
  32705. // matricesIndices
  32706. var matricesIndices = parsedVertexData.matricesIndices;
  32707. if (matricesIndices) {
  32708. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32709. }
  32710. // matricesWeights
  32711. var matricesWeights = parsedVertexData.matricesWeights;
  32712. if (matricesWeights) {
  32713. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32714. }
  32715. // indices
  32716. var indices = parsedVertexData.indices;
  32717. if (indices) {
  32718. vertexData.indices = indices;
  32719. }
  32720. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32721. };
  32722. return VertexData;
  32723. }());
  32724. BABYLON.VertexData = VertexData;
  32725. })(BABYLON || (BABYLON = {}));
  32726. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32727. var BABYLON;
  32728. (function (BABYLON) {
  32729. /**
  32730. * Class used to store geometry data (vertex buffers + index buffer)
  32731. */
  32732. var Geometry = /** @class */ (function () {
  32733. /**
  32734. * Creates a new geometry
  32735. * @param id defines the unique ID
  32736. * @param scene defines the hosting scene
  32737. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32738. * @param updatable defines if geometry must be updatable (false by default)
  32739. * @param mesh defines the mesh that will be associated with the geometry
  32740. */
  32741. function Geometry(id, scene, vertexData, updatable, mesh) {
  32742. if (updatable === void 0) { updatable = false; }
  32743. if (mesh === void 0) { mesh = null; }
  32744. /**
  32745. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32746. */
  32747. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32748. this._totalVertices = 0;
  32749. this._isDisposed = false;
  32750. this._indexBufferIsUpdatable = false;
  32751. this.id = id;
  32752. this._engine = scene.getEngine();
  32753. this._meshes = [];
  32754. this._scene = scene;
  32755. //Init vertex buffer cache
  32756. this._vertexBuffers = {};
  32757. this._indices = [];
  32758. this._updatable = updatable;
  32759. // vertexData
  32760. if (vertexData) {
  32761. this.setAllVerticesData(vertexData, updatable);
  32762. }
  32763. else {
  32764. this._totalVertices = 0;
  32765. this._indices = [];
  32766. }
  32767. if (this._engine.getCaps().vertexArrayObject) {
  32768. this._vertexArrayObjects = {};
  32769. }
  32770. // applyToMesh
  32771. if (mesh) {
  32772. if (mesh.getClassName() === "LinesMesh") {
  32773. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32774. this.updateExtend();
  32775. }
  32776. this.applyToMesh(mesh);
  32777. mesh.computeWorldMatrix(true);
  32778. }
  32779. }
  32780. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32781. /**
  32782. * 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
  32783. */
  32784. get: function () {
  32785. return this._boundingBias;
  32786. },
  32787. /**
  32788. * 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
  32789. */
  32790. set: function (value) {
  32791. if (this._boundingBias && this._boundingBias.equals(value)) {
  32792. return;
  32793. }
  32794. this._boundingBias = value.clone();
  32795. this.updateBoundingInfo(true, null);
  32796. },
  32797. enumerable: true,
  32798. configurable: true
  32799. });
  32800. /**
  32801. * Static function used to attach a new empty geometry to a mesh
  32802. * @param mesh defines the mesh to attach the geometry to
  32803. * @returns the new {BABYLON.Geometry}
  32804. */
  32805. Geometry.CreateGeometryForMesh = function (mesh) {
  32806. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32807. geometry.applyToMesh(mesh);
  32808. return geometry;
  32809. };
  32810. Object.defineProperty(Geometry.prototype, "extend", {
  32811. /**
  32812. * Gets the current extend of the geometry
  32813. */
  32814. get: function () {
  32815. return this._extend;
  32816. },
  32817. enumerable: true,
  32818. configurable: true
  32819. });
  32820. /**
  32821. * Gets the hosting scene
  32822. * @returns the hosting {BABYLON.Scene}
  32823. */
  32824. Geometry.prototype.getScene = function () {
  32825. return this._scene;
  32826. };
  32827. /**
  32828. * Gets the hosting engine
  32829. * @returns the hosting {BABYLON.Engine}
  32830. */
  32831. Geometry.prototype.getEngine = function () {
  32832. return this._engine;
  32833. };
  32834. /**
  32835. * Defines if the geometry is ready to use
  32836. * @returns true if the geometry is ready to be used
  32837. */
  32838. Geometry.prototype.isReady = function () {
  32839. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32840. };
  32841. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32842. /**
  32843. * Gets a value indicating that the geometry should not be serialized
  32844. */
  32845. get: function () {
  32846. for (var index = 0; index < this._meshes.length; index++) {
  32847. if (!this._meshes[index].doNotSerialize) {
  32848. return false;
  32849. }
  32850. }
  32851. return true;
  32852. },
  32853. enumerable: true,
  32854. configurable: true
  32855. });
  32856. /** @ignore */
  32857. Geometry.prototype._rebuild = function () {
  32858. if (this._vertexArrayObjects) {
  32859. this._vertexArrayObjects = {};
  32860. }
  32861. // Index buffer
  32862. if (this._meshes.length !== 0 && this._indices) {
  32863. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32864. }
  32865. // Vertex buffers
  32866. for (var key in this._vertexBuffers) {
  32867. var vertexBuffer = this._vertexBuffers[key];
  32868. vertexBuffer._rebuild();
  32869. }
  32870. };
  32871. /**
  32872. * Affects all gemetry data in one call
  32873. * @param vertexData defines the geometry data
  32874. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32875. */
  32876. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32877. vertexData.applyToGeometry(this, updatable);
  32878. this.notifyUpdate();
  32879. };
  32880. /**
  32881. * Set specific vertex data
  32882. * @param kind defines the data kind (Position, normal, etc...)
  32883. * @param data defines the vertex data to use
  32884. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32885. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32886. */
  32887. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32888. if (updatable === void 0) { updatable = false; }
  32889. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32890. this.setVerticesBuffer(buffer);
  32891. };
  32892. /**
  32893. * Removes a specific vertex data
  32894. * @param kind defines the data kind (Position, normal, etc...)
  32895. */
  32896. Geometry.prototype.removeVerticesData = function (kind) {
  32897. if (this._vertexBuffers[kind]) {
  32898. this._vertexBuffers[kind].dispose();
  32899. delete this._vertexBuffers[kind];
  32900. }
  32901. };
  32902. /**
  32903. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32904. * @param buffer defines the vertex buffer to use
  32905. */
  32906. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32907. var kind = buffer.getKind();
  32908. if (this._vertexBuffers[kind]) {
  32909. this._vertexBuffers[kind].dispose();
  32910. }
  32911. this._vertexBuffers[kind] = buffer;
  32912. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32913. var data = buffer.getData();
  32914. var stride = buffer.getStrideSize();
  32915. this._totalVertices = data.length / stride;
  32916. this.updateExtend(data, stride);
  32917. this._resetPointsArrayCache();
  32918. var meshes = this._meshes;
  32919. var numOfMeshes = meshes.length;
  32920. for (var index = 0; index < numOfMeshes; index++) {
  32921. var mesh = meshes[index];
  32922. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32923. mesh._createGlobalSubMesh(false);
  32924. mesh.computeWorldMatrix(true);
  32925. }
  32926. }
  32927. this.notifyUpdate(kind);
  32928. if (this._vertexArrayObjects) {
  32929. this._disposeVertexArrayObjects();
  32930. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32931. }
  32932. };
  32933. /**
  32934. * Update a specific vertex buffer
  32935. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32936. * It will do nothing if the buffer is not updatable
  32937. * @param kind defines the data kind (Position, normal, etc...)
  32938. * @param data defines the data to use
  32939. * @param offset defines the offset in the target buffer where to store the data
  32940. */
  32941. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32942. var vertexBuffer = this.getVertexBuffer(kind);
  32943. if (!vertexBuffer) {
  32944. return;
  32945. }
  32946. vertexBuffer.updateDirectly(data, offset);
  32947. this.notifyUpdate(kind);
  32948. };
  32949. /**
  32950. * Update a specific vertex buffer
  32951. * This function will create a new buffer if the current one is not updatable
  32952. * @param kind defines the data kind (Position, normal, etc...)
  32953. * @param data defines the data to use
  32954. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32955. */
  32956. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32957. if (updateExtends === void 0) { updateExtends = false; }
  32958. var vertexBuffer = this.getVertexBuffer(kind);
  32959. if (!vertexBuffer) {
  32960. return;
  32961. }
  32962. vertexBuffer.update(data);
  32963. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32964. var stride = vertexBuffer.getStrideSize();
  32965. this._totalVertices = data.length / stride;
  32966. this.updateBoundingInfo(updateExtends, data);
  32967. }
  32968. this.notifyUpdate(kind);
  32969. };
  32970. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32971. if (updateExtends) {
  32972. this.updateExtend(data);
  32973. }
  32974. var meshes = this._meshes;
  32975. var numOfMeshes = meshes.length;
  32976. this._resetPointsArrayCache();
  32977. for (var index = 0; index < numOfMeshes; index++) {
  32978. var mesh = meshes[index];
  32979. if (updateExtends) {
  32980. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32981. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32982. var subMesh = mesh.subMeshes[subIndex];
  32983. subMesh.refreshBoundingInfo();
  32984. }
  32985. }
  32986. }
  32987. };
  32988. /** @ignore */
  32989. Geometry.prototype._bind = function (effect, indexToBind) {
  32990. if (!effect) {
  32991. return;
  32992. }
  32993. if (indexToBind === undefined) {
  32994. indexToBind = this._indexBuffer;
  32995. }
  32996. var vbs = this.getVertexBuffers();
  32997. if (!vbs) {
  32998. return;
  32999. }
  33000. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  33001. this._engine.bindBuffers(vbs, indexToBind, effect);
  33002. return;
  33003. }
  33004. // Using VAO
  33005. if (!this._vertexArrayObjects[effect.key]) {
  33006. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  33007. }
  33008. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  33009. };
  33010. /**
  33011. * Gets total number of vertices
  33012. * @returns the total number of vertices
  33013. */
  33014. Geometry.prototype.getTotalVertices = function () {
  33015. if (!this.isReady()) {
  33016. return 0;
  33017. }
  33018. return this._totalVertices;
  33019. };
  33020. /**
  33021. * Gets a specific vertex data attached to this geometry
  33022. * @param kind defines the data kind (Position, normal, etc...)
  33023. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33024. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  33025. * @returns a float array containing vertex data
  33026. */
  33027. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  33028. var vertexBuffer = this.getVertexBuffer(kind);
  33029. if (!vertexBuffer) {
  33030. return null;
  33031. }
  33032. var orig = vertexBuffer.getData();
  33033. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  33034. return orig;
  33035. }
  33036. else {
  33037. var len = orig.length;
  33038. var copy = [];
  33039. for (var i = 0; i < len; i++) {
  33040. copy.push(orig[i]);
  33041. }
  33042. return copy;
  33043. }
  33044. };
  33045. /**
  33046. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  33047. * @param kind defines the data kind (Position, normal, etc...)
  33048. * @returns true if the vertex buffer with the specified kind is updatable
  33049. */
  33050. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  33051. var vb = this._vertexBuffers[kind];
  33052. if (!vb) {
  33053. return false;
  33054. }
  33055. return vb.isUpdatable();
  33056. };
  33057. /**
  33058. * Gets a specific vertex buffer
  33059. * @param kind defines the data kind (Position, normal, etc...)
  33060. * @returns a {BABYLON.VertexBuffer}
  33061. */
  33062. Geometry.prototype.getVertexBuffer = function (kind) {
  33063. if (!this.isReady()) {
  33064. return null;
  33065. }
  33066. return this._vertexBuffers[kind];
  33067. };
  33068. /**
  33069. * Returns all vertex buffers
  33070. * @return an object holding all vertex buffers indexed by kind
  33071. */
  33072. Geometry.prototype.getVertexBuffers = function () {
  33073. if (!this.isReady()) {
  33074. return null;
  33075. }
  33076. return this._vertexBuffers;
  33077. };
  33078. /**
  33079. * Gets a boolean indicating if specific vertex buffer is present
  33080. * @param kind defines the data kind (Position, normal, etc...)
  33081. * @returns true if data is present
  33082. */
  33083. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33084. if (!this._vertexBuffers) {
  33085. if (this._delayInfo) {
  33086. return this._delayInfo.indexOf(kind) !== -1;
  33087. }
  33088. return false;
  33089. }
  33090. return this._vertexBuffers[kind] !== undefined;
  33091. };
  33092. /**
  33093. * Gets a list of all attached data kinds (Position, normal, etc...)
  33094. * @returns a list of string containing all kinds
  33095. */
  33096. Geometry.prototype.getVerticesDataKinds = function () {
  33097. var result = [];
  33098. var kind;
  33099. if (!this._vertexBuffers && this._delayInfo) {
  33100. for (kind in this._delayInfo) {
  33101. result.push(kind);
  33102. }
  33103. }
  33104. else {
  33105. for (kind in this._vertexBuffers) {
  33106. result.push(kind);
  33107. }
  33108. }
  33109. return result;
  33110. };
  33111. /**
  33112. * Update index buffer
  33113. * @param indices defines the indices to store in the index buffer
  33114. * @param offset defines the offset in the target buffer where to store the data
  33115. */
  33116. Geometry.prototype.updateIndices = function (indices, offset) {
  33117. if (!this._indexBuffer) {
  33118. return;
  33119. }
  33120. if (!this._indexBufferIsUpdatable) {
  33121. this.setIndices(indices, null, true);
  33122. }
  33123. else {
  33124. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  33125. }
  33126. };
  33127. /**
  33128. * Creates a new index buffer
  33129. * @param indices defines the indices to store in the index buffer
  33130. * @param totalVertices defines the total number of vertices (could be null)
  33131. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  33132. */
  33133. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  33134. if (totalVertices === void 0) { totalVertices = null; }
  33135. if (updatable === void 0) { updatable = false; }
  33136. if (this._indexBuffer) {
  33137. this._engine._releaseBuffer(this._indexBuffer);
  33138. }
  33139. this._disposeVertexArrayObjects();
  33140. this._indices = indices;
  33141. this._indexBufferIsUpdatable = updatable;
  33142. if (this._meshes.length !== 0 && this._indices) {
  33143. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33144. }
  33145. if (totalVertices != undefined) {
  33146. this._totalVertices = totalVertices;
  33147. }
  33148. var meshes = this._meshes;
  33149. var numOfMeshes = meshes.length;
  33150. for (var index = 0; index < numOfMeshes; index++) {
  33151. meshes[index]._createGlobalSubMesh(true);
  33152. }
  33153. this.notifyUpdate();
  33154. };
  33155. /**
  33156. * Return the total number of indices
  33157. * @returns the total number of indices
  33158. */
  33159. Geometry.prototype.getTotalIndices = function () {
  33160. if (!this.isReady()) {
  33161. return 0;
  33162. }
  33163. return this._indices.length;
  33164. };
  33165. /**
  33166. * Gets the index buffer array
  33167. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33168. * @returns the index buffer array
  33169. */
  33170. Geometry.prototype.getIndices = function (copyWhenShared) {
  33171. if (!this.isReady()) {
  33172. return null;
  33173. }
  33174. var orig = this._indices;
  33175. if (!copyWhenShared || this._meshes.length === 1) {
  33176. return orig;
  33177. }
  33178. else {
  33179. var len = orig.length;
  33180. var copy = [];
  33181. for (var i = 0; i < len; i++) {
  33182. copy.push(orig[i]);
  33183. }
  33184. return copy;
  33185. }
  33186. };
  33187. /**
  33188. * Gets the index buffer
  33189. * @return the index buffer
  33190. */
  33191. Geometry.prototype.getIndexBuffer = function () {
  33192. if (!this.isReady()) {
  33193. return null;
  33194. }
  33195. return this._indexBuffer;
  33196. };
  33197. /** @ignore */
  33198. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33199. if (effect === void 0) { effect = null; }
  33200. if (!effect || !this._vertexArrayObjects) {
  33201. return;
  33202. }
  33203. if (this._vertexArrayObjects[effect.key]) {
  33204. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33205. delete this._vertexArrayObjects[effect.key];
  33206. }
  33207. };
  33208. /**
  33209. * Release the associated resources for a specific mesh
  33210. * @param mesh defines the source mesh
  33211. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33212. */
  33213. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33214. var meshes = this._meshes;
  33215. var index = meshes.indexOf(mesh);
  33216. if (index === -1) {
  33217. return;
  33218. }
  33219. meshes.splice(index, 1);
  33220. mesh._geometry = null;
  33221. if (meshes.length === 0 && shouldDispose) {
  33222. this.dispose();
  33223. }
  33224. };
  33225. /**
  33226. * Apply current geometry to a given mesh
  33227. * @param mesh defines the mesh to apply geometry to
  33228. */
  33229. Geometry.prototype.applyToMesh = function (mesh) {
  33230. if (mesh._geometry === this) {
  33231. return;
  33232. }
  33233. var previousGeometry = mesh._geometry;
  33234. if (previousGeometry) {
  33235. previousGeometry.releaseForMesh(mesh);
  33236. }
  33237. var meshes = this._meshes;
  33238. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33239. mesh._geometry = this;
  33240. this._scene.pushGeometry(this);
  33241. meshes.push(mesh);
  33242. if (this.isReady()) {
  33243. this._applyToMesh(mesh);
  33244. }
  33245. else {
  33246. mesh._boundingInfo = this._boundingInfo;
  33247. }
  33248. };
  33249. Geometry.prototype.updateExtend = function (data, stride) {
  33250. if (data === void 0) { data = null; }
  33251. if (!data) {
  33252. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33253. }
  33254. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33255. };
  33256. Geometry.prototype._applyToMesh = function (mesh) {
  33257. var numOfMeshes = this._meshes.length;
  33258. // vertexBuffers
  33259. for (var kind in this._vertexBuffers) {
  33260. if (numOfMeshes === 1) {
  33261. this._vertexBuffers[kind].create();
  33262. }
  33263. var buffer = this._vertexBuffers[kind].getBuffer();
  33264. if (buffer)
  33265. buffer.references = numOfMeshes;
  33266. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33267. if (!this._extend) {
  33268. this.updateExtend(this._vertexBuffers[kind].getData());
  33269. }
  33270. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33271. mesh._createGlobalSubMesh(false);
  33272. //bounding info was just created again, world matrix should be applied again.
  33273. mesh._updateBoundingInfo();
  33274. }
  33275. }
  33276. // indexBuffer
  33277. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33278. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33279. }
  33280. if (this._indexBuffer) {
  33281. this._indexBuffer.references = numOfMeshes;
  33282. }
  33283. };
  33284. Geometry.prototype.notifyUpdate = function (kind) {
  33285. if (this.onGeometryUpdated) {
  33286. this.onGeometryUpdated(this, kind);
  33287. }
  33288. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33289. var mesh = _a[_i];
  33290. mesh._markSubMeshesAsAttributesDirty();
  33291. }
  33292. };
  33293. /**
  33294. * Load the geometry if it was flagged as delay loaded
  33295. * @param scene defines the hosting scene
  33296. * @param onLoaded defines a callback called when the geometry is loaded
  33297. */
  33298. Geometry.prototype.load = function (scene, onLoaded) {
  33299. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33300. return;
  33301. }
  33302. if (this.isReady()) {
  33303. if (onLoaded) {
  33304. onLoaded();
  33305. }
  33306. return;
  33307. }
  33308. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33309. this._queueLoad(scene, onLoaded);
  33310. };
  33311. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33312. var _this = this;
  33313. if (!this.delayLoadingFile) {
  33314. return;
  33315. }
  33316. scene._addPendingData(this);
  33317. scene._loadFile(this.delayLoadingFile, function (data) {
  33318. if (!_this._delayLoadingFunction) {
  33319. return;
  33320. }
  33321. _this._delayLoadingFunction(JSON.parse(data), _this);
  33322. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33323. _this._delayInfo = [];
  33324. scene._removePendingData(_this);
  33325. var meshes = _this._meshes;
  33326. var numOfMeshes = meshes.length;
  33327. for (var index = 0; index < numOfMeshes; index++) {
  33328. _this._applyToMesh(meshes[index]);
  33329. }
  33330. if (onLoaded) {
  33331. onLoaded();
  33332. }
  33333. }, undefined, true);
  33334. };
  33335. /**
  33336. * Invert the geometry to move from a right handed system to a left handed one.
  33337. */
  33338. Geometry.prototype.toLeftHanded = function () {
  33339. // Flip faces
  33340. var tIndices = this.getIndices(false);
  33341. if (tIndices != null && tIndices.length > 0) {
  33342. for (var i = 0; i < tIndices.length; i += 3) {
  33343. var tTemp = tIndices[i + 0];
  33344. tIndices[i + 0] = tIndices[i + 2];
  33345. tIndices[i + 2] = tTemp;
  33346. }
  33347. this.setIndices(tIndices);
  33348. }
  33349. // Negate position.z
  33350. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33351. if (tPositions != null && tPositions.length > 0) {
  33352. for (var i = 0; i < tPositions.length; i += 3) {
  33353. tPositions[i + 2] = -tPositions[i + 2];
  33354. }
  33355. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33356. }
  33357. // Negate normal.z
  33358. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33359. if (tNormals != null && tNormals.length > 0) {
  33360. for (var i = 0; i < tNormals.length; i += 3) {
  33361. tNormals[i + 2] = -tNormals[i + 2];
  33362. }
  33363. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33364. }
  33365. };
  33366. // Cache
  33367. /** @ignore */
  33368. Geometry.prototype._resetPointsArrayCache = function () {
  33369. this._positions = null;
  33370. };
  33371. /** @ignore */
  33372. Geometry.prototype._generatePointsArray = function () {
  33373. if (this._positions)
  33374. return true;
  33375. this._positions = [];
  33376. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33377. if (!data) {
  33378. return false;
  33379. }
  33380. for (var index = 0; index < data.length; index += 3) {
  33381. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33382. }
  33383. return true;
  33384. };
  33385. /**
  33386. * Gets a value indicating if the geometry is disposed
  33387. * @returns true if the geometry was disposed
  33388. */
  33389. Geometry.prototype.isDisposed = function () {
  33390. return this._isDisposed;
  33391. };
  33392. Geometry.prototype._disposeVertexArrayObjects = function () {
  33393. if (this._vertexArrayObjects) {
  33394. for (var kind in this._vertexArrayObjects) {
  33395. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33396. }
  33397. this._vertexArrayObjects = {};
  33398. }
  33399. };
  33400. /**
  33401. * Free all associated resources
  33402. */
  33403. Geometry.prototype.dispose = function () {
  33404. var meshes = this._meshes;
  33405. var numOfMeshes = meshes.length;
  33406. var index;
  33407. for (index = 0; index < numOfMeshes; index++) {
  33408. this.releaseForMesh(meshes[index]);
  33409. }
  33410. this._meshes = [];
  33411. this._disposeVertexArrayObjects();
  33412. for (var kind in this._vertexBuffers) {
  33413. this._vertexBuffers[kind].dispose();
  33414. }
  33415. this._vertexBuffers = {};
  33416. this._totalVertices = 0;
  33417. if (this._indexBuffer) {
  33418. this._engine._releaseBuffer(this._indexBuffer);
  33419. }
  33420. this._indexBuffer = null;
  33421. this._indices = [];
  33422. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33423. this.delayLoadingFile = null;
  33424. this._delayLoadingFunction = null;
  33425. this._delayInfo = [];
  33426. this._boundingInfo = null;
  33427. this._scene.removeGeometry(this);
  33428. this._isDisposed = true;
  33429. };
  33430. /**
  33431. * Clone the current geometry into a new geometry
  33432. * @param id defines the unique ID of the new geometry
  33433. * @returns a new geometry object
  33434. */
  33435. Geometry.prototype.copy = function (id) {
  33436. var vertexData = new BABYLON.VertexData();
  33437. vertexData.indices = [];
  33438. var indices = this.getIndices();
  33439. if (indices) {
  33440. for (var index = 0; index < indices.length; index++) {
  33441. vertexData.indices.push(indices[index]);
  33442. }
  33443. }
  33444. var updatable = false;
  33445. var stopChecking = false;
  33446. var kind;
  33447. for (kind in this._vertexBuffers) {
  33448. // using slice() to make a copy of the array and not just reference it
  33449. var data = this.getVerticesData(kind);
  33450. if (data instanceof Float32Array) {
  33451. vertexData.set(new Float32Array(data), kind);
  33452. }
  33453. else {
  33454. vertexData.set(data.slice(0), kind);
  33455. }
  33456. if (!stopChecking) {
  33457. var vb = this.getVertexBuffer(kind);
  33458. if (vb) {
  33459. updatable = vb.isUpdatable();
  33460. stopChecking = !updatable;
  33461. }
  33462. }
  33463. }
  33464. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33465. geometry.delayLoadState = this.delayLoadState;
  33466. geometry.delayLoadingFile = this.delayLoadingFile;
  33467. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33468. for (kind in this._delayInfo) {
  33469. geometry._delayInfo = geometry._delayInfo || [];
  33470. geometry._delayInfo.push(kind);
  33471. }
  33472. // Bounding info
  33473. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33474. return geometry;
  33475. };
  33476. /**
  33477. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33478. * @return a JSON representation of the current geometry data (without the vertices data)
  33479. */
  33480. Geometry.prototype.serialize = function () {
  33481. var serializationObject = {};
  33482. serializationObject.id = this.id;
  33483. serializationObject.updatable = this._updatable;
  33484. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33485. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33486. }
  33487. return serializationObject;
  33488. };
  33489. Geometry.prototype.toNumberArray = function (origin) {
  33490. if (Array.isArray(origin)) {
  33491. return origin;
  33492. }
  33493. else {
  33494. return Array.prototype.slice.call(origin);
  33495. }
  33496. };
  33497. /**
  33498. * Serialize all vertices data into a JSON oject
  33499. * @returns a JSON representation of the current geometry data
  33500. */
  33501. Geometry.prototype.serializeVerticeData = function () {
  33502. var serializationObject = this.serialize();
  33503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33504. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33505. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33506. serializationObject.positions._updatable = true;
  33507. }
  33508. }
  33509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33510. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33511. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33512. serializationObject.normals._updatable = true;
  33513. }
  33514. }
  33515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33516. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33518. serializationObject.tangets._updatable = true;
  33519. }
  33520. }
  33521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33522. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33524. serializationObject.uvs._updatable = true;
  33525. }
  33526. }
  33527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33528. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33529. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33530. serializationObject.uv2s._updatable = true;
  33531. }
  33532. }
  33533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33534. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33535. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33536. serializationObject.uv3s._updatable = true;
  33537. }
  33538. }
  33539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33540. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33541. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33542. serializationObject.uv4s._updatable = true;
  33543. }
  33544. }
  33545. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33546. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33547. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33548. serializationObject.uv5s._updatable = true;
  33549. }
  33550. }
  33551. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33552. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33553. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33554. serializationObject.uv6s._updatable = true;
  33555. }
  33556. }
  33557. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33558. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33559. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33560. serializationObject.colors._updatable = true;
  33561. }
  33562. }
  33563. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33564. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33565. serializationObject.matricesIndices._isExpanded = true;
  33566. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33567. serializationObject.matricesIndices._updatable = true;
  33568. }
  33569. }
  33570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33571. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33572. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33573. serializationObject.matricesWeights._updatable = true;
  33574. }
  33575. }
  33576. serializationObject.indices = this.toNumberArray(this.getIndices());
  33577. return serializationObject;
  33578. };
  33579. // Statics
  33580. /**
  33581. * Extracts a clone of a mesh geometry
  33582. * @param mesh defines the source mesh
  33583. * @param id defines the unique ID of the new geometry object
  33584. * @returns the new geometry object
  33585. */
  33586. Geometry.ExtractFromMesh = function (mesh, id) {
  33587. var geometry = mesh._geometry;
  33588. if (!geometry) {
  33589. return null;
  33590. }
  33591. return geometry.copy(id);
  33592. };
  33593. /**
  33594. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33595. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33596. * Be aware Math.random() could cause collisions, but:
  33597. * "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"
  33598. * @returns a string containing a new GUID
  33599. */
  33600. Geometry.RandomId = function () {
  33601. return BABYLON.Tools.RandomId();
  33602. };
  33603. /** @ignore */
  33604. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33605. var scene = mesh.getScene();
  33606. // Geometry
  33607. var geometryId = parsedGeometry.geometryId;
  33608. if (geometryId) {
  33609. var geometry = scene.getGeometryByID(geometryId);
  33610. if (geometry) {
  33611. geometry.applyToMesh(mesh);
  33612. }
  33613. }
  33614. else if (parsedGeometry instanceof ArrayBuffer) {
  33615. var binaryInfo = mesh._binaryInfo;
  33616. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33617. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33618. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33619. }
  33620. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33621. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33622. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33623. }
  33624. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33625. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33626. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33627. }
  33628. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33629. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33630. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33631. }
  33632. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33633. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33634. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33635. }
  33636. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33637. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33638. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33639. }
  33640. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33641. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33642. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33643. }
  33644. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33645. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33646. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33647. }
  33648. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33649. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33650. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33651. }
  33652. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33653. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33654. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33655. }
  33656. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33657. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33658. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33659. }
  33660. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33661. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33662. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33663. }
  33664. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33665. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33666. mesh.setIndices(indicesData, null);
  33667. }
  33668. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33669. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33670. mesh.subMeshes = [];
  33671. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33672. var materialIndex = subMeshesData[(i * 5) + 0];
  33673. var verticesStart = subMeshesData[(i * 5) + 1];
  33674. var verticesCount = subMeshesData[(i * 5) + 2];
  33675. var indexStart = subMeshesData[(i * 5) + 3];
  33676. var indexCount = subMeshesData[(i * 5) + 4];
  33677. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33678. }
  33679. }
  33680. }
  33681. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33682. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33683. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33684. if (parsedGeometry.tangents) {
  33685. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33686. }
  33687. if (parsedGeometry.uvs) {
  33688. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33689. }
  33690. if (parsedGeometry.uvs2) {
  33691. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33692. }
  33693. if (parsedGeometry.uvs3) {
  33694. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33695. }
  33696. if (parsedGeometry.uvs4) {
  33697. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33698. }
  33699. if (parsedGeometry.uvs5) {
  33700. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33701. }
  33702. if (parsedGeometry.uvs6) {
  33703. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33704. }
  33705. if (parsedGeometry.colors) {
  33706. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33707. }
  33708. if (parsedGeometry.matricesIndices) {
  33709. if (!parsedGeometry.matricesIndices._isExpanded) {
  33710. var floatIndices = [];
  33711. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33712. var matricesIndex = parsedGeometry.matricesIndices[i];
  33713. floatIndices.push(matricesIndex & 0x000000FF);
  33714. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33715. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33716. floatIndices.push(matricesIndex >> 24);
  33717. }
  33718. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33719. }
  33720. else {
  33721. delete parsedGeometry.matricesIndices._isExpanded;
  33722. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33723. }
  33724. }
  33725. if (parsedGeometry.matricesIndicesExtra) {
  33726. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33727. var floatIndices = [];
  33728. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33729. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33730. floatIndices.push(matricesIndex & 0x000000FF);
  33731. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33732. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33733. floatIndices.push(matricesIndex >> 24);
  33734. }
  33735. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33736. }
  33737. else {
  33738. delete parsedGeometry.matricesIndices._isExpanded;
  33739. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33740. }
  33741. }
  33742. if (parsedGeometry.matricesWeights) {
  33743. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33744. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33745. }
  33746. if (parsedGeometry.matricesWeightsExtra) {
  33747. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33748. }
  33749. mesh.setIndices(parsedGeometry.indices, null);
  33750. }
  33751. // SubMeshes
  33752. if (parsedGeometry.subMeshes) {
  33753. mesh.subMeshes = [];
  33754. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33755. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33756. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33757. }
  33758. }
  33759. // Flat shading
  33760. if (mesh._shouldGenerateFlatShading) {
  33761. mesh.convertToFlatShadedMesh();
  33762. delete mesh._shouldGenerateFlatShading;
  33763. }
  33764. // Update
  33765. mesh.computeWorldMatrix(true);
  33766. // Octree
  33767. var sceneOctree = scene.selectionOctree;
  33768. if (sceneOctree !== undefined && sceneOctree !== null) {
  33769. sceneOctree.addMesh(mesh);
  33770. }
  33771. };
  33772. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33773. var epsilon = 1e-3;
  33774. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33775. return;
  33776. }
  33777. var noInfluenceBoneIndex = 0.0;
  33778. if (parsedGeometry.skeletonId > -1) {
  33779. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33780. if (!skeleton) {
  33781. return;
  33782. }
  33783. noInfluenceBoneIndex = skeleton.bones.length;
  33784. }
  33785. else {
  33786. return;
  33787. }
  33788. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33789. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33790. var matricesWeights = parsedGeometry.matricesWeights;
  33791. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33792. var influencers = parsedGeometry.numBoneInfluencer;
  33793. var size = matricesWeights.length;
  33794. for (var i = 0; i < size; i += 4) {
  33795. var weight = 0.0;
  33796. var firstZeroWeight = -1;
  33797. for (var j = 0; j < 4; j++) {
  33798. var w = matricesWeights[i + j];
  33799. weight += w;
  33800. if (w < epsilon && firstZeroWeight < 0) {
  33801. firstZeroWeight = j;
  33802. }
  33803. }
  33804. if (matricesWeightsExtra) {
  33805. for (var j = 0; j < 4; j++) {
  33806. var w = matricesWeightsExtra[i + j];
  33807. weight += w;
  33808. if (w < epsilon && firstZeroWeight < 0) {
  33809. firstZeroWeight = j + 4;
  33810. }
  33811. }
  33812. }
  33813. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33814. firstZeroWeight = influencers - 1;
  33815. }
  33816. if (weight > epsilon) {
  33817. var mweight = 1.0 / weight;
  33818. for (var j = 0; j < 4; j++) {
  33819. matricesWeights[i + j] *= mweight;
  33820. }
  33821. if (matricesWeightsExtra) {
  33822. for (var j = 0; j < 4; j++) {
  33823. matricesWeightsExtra[i + j] *= mweight;
  33824. }
  33825. }
  33826. }
  33827. else {
  33828. if (firstZeroWeight >= 4) {
  33829. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33830. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33831. }
  33832. else {
  33833. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33834. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33835. }
  33836. }
  33837. }
  33838. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33839. if (parsedGeometry.matricesWeightsExtra) {
  33840. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33841. }
  33842. };
  33843. /**
  33844. * Create a new geometry from persisted data (Using .babylon file format)
  33845. * @param parsedVertexData defines the persisted data
  33846. * @param scene defines the hosting scene
  33847. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33848. * @returns the new geometry object
  33849. */
  33850. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33851. if (scene.getGeometryByID(parsedVertexData.id)) {
  33852. return null; // null since geometry could be something else than a box...
  33853. }
  33854. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33855. if (BABYLON.Tags) {
  33856. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33857. }
  33858. if (parsedVertexData.delayLoadingFile) {
  33859. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33860. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33861. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33862. geometry._delayInfo = [];
  33863. if (parsedVertexData.hasUVs) {
  33864. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33865. }
  33866. if (parsedVertexData.hasUVs2) {
  33867. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33868. }
  33869. if (parsedVertexData.hasUVs3) {
  33870. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33871. }
  33872. if (parsedVertexData.hasUVs4) {
  33873. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33874. }
  33875. if (parsedVertexData.hasUVs5) {
  33876. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33877. }
  33878. if (parsedVertexData.hasUVs6) {
  33879. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33880. }
  33881. if (parsedVertexData.hasColors) {
  33882. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33883. }
  33884. if (parsedVertexData.hasMatricesIndices) {
  33885. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33886. }
  33887. if (parsedVertexData.hasMatricesWeights) {
  33888. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33889. }
  33890. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33891. }
  33892. else {
  33893. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33894. }
  33895. scene.pushGeometry(geometry, true);
  33896. return geometry;
  33897. };
  33898. return Geometry;
  33899. }());
  33900. BABYLON.Geometry = Geometry;
  33901. // Primitives
  33902. /// Abstract class
  33903. /**
  33904. * Abstract class used to provide common services for all typed geometries
  33905. */
  33906. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33907. __extends(_PrimitiveGeometry, _super);
  33908. /**
  33909. * Creates a new typed geometry
  33910. * @param id defines the unique ID of the geometry
  33911. * @param scene defines the hosting scene
  33912. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33913. * @param mesh defines the hosting mesh (can be null)
  33914. */
  33915. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33916. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33917. if (mesh === void 0) { mesh = null; }
  33918. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33919. _this._canBeRegenerated = _canBeRegenerated;
  33920. _this._beingRegenerated = true;
  33921. _this.regenerate();
  33922. _this._beingRegenerated = false;
  33923. return _this;
  33924. }
  33925. /**
  33926. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33927. * @returns true if the geometry can be regenerated
  33928. */
  33929. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33930. return this._canBeRegenerated;
  33931. };
  33932. /**
  33933. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33934. */
  33935. _PrimitiveGeometry.prototype.regenerate = function () {
  33936. if (!this._canBeRegenerated) {
  33937. return;
  33938. }
  33939. this._beingRegenerated = true;
  33940. this.setAllVerticesData(this._regenerateVertexData(), false);
  33941. this._beingRegenerated = false;
  33942. };
  33943. /**
  33944. * Clone the geometry
  33945. * @param id defines the unique ID of the new geometry
  33946. * @returns the new geometry
  33947. */
  33948. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33949. return _super.prototype.copy.call(this, id);
  33950. };
  33951. // overrides
  33952. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33953. if (!this._beingRegenerated) {
  33954. return;
  33955. }
  33956. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33957. };
  33958. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33959. if (!this._beingRegenerated) {
  33960. return;
  33961. }
  33962. _super.prototype.setVerticesData.call(this, kind, data, false);
  33963. };
  33964. // to override
  33965. /** @ignore */
  33966. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33967. throw new Error("Abstract method");
  33968. };
  33969. _PrimitiveGeometry.prototype.copy = function (id) {
  33970. throw new Error("Must be overriden in sub-classes.");
  33971. };
  33972. _PrimitiveGeometry.prototype.serialize = function () {
  33973. var serializationObject = _super.prototype.serialize.call(this);
  33974. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33975. return serializationObject;
  33976. };
  33977. return _PrimitiveGeometry;
  33978. }(Geometry));
  33979. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33980. /**
  33981. * Creates a ribbon geometry
  33982. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33983. */
  33984. var RibbonGeometry = /** @class */ (function (_super) {
  33985. __extends(RibbonGeometry, _super);
  33986. /**
  33987. * Creates a ribbon geometry
  33988. * @param id defines the unique ID of the geometry
  33989. * @param scene defines the hosting scene
  33990. * @param pathArray defines the array of paths to use
  33991. * @param closeArray defines if the last path and the first path must be joined
  33992. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33993. * @param offset defines the offset between points
  33994. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33995. * @param mesh defines the hosting mesh (can be null)
  33996. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33997. */
  33998. function RibbonGeometry(id, scene,
  33999. /**
  34000. * Defines the array of paths to use
  34001. */
  34002. pathArray,
  34003. /**
  34004. * Defines if the last and first points of each path in your pathArray must be joined
  34005. */
  34006. closeArray,
  34007. /**
  34008. * Defines if the last and first points of each path in your pathArray must be joined
  34009. */
  34010. closePath,
  34011. /**
  34012. * Defines the offset between points
  34013. */
  34014. offset, canBeRegenerated, mesh,
  34015. /**
  34016. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34017. */
  34018. side) {
  34019. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34020. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34021. _this.pathArray = pathArray;
  34022. _this.closeArray = closeArray;
  34023. _this.closePath = closePath;
  34024. _this.offset = offset;
  34025. _this.side = side;
  34026. return _this;
  34027. }
  34028. /** @ignore */
  34029. RibbonGeometry.prototype._regenerateVertexData = function () {
  34030. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34031. };
  34032. RibbonGeometry.prototype.copy = function (id) {
  34033. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  34034. };
  34035. return RibbonGeometry;
  34036. }(_PrimitiveGeometry));
  34037. BABYLON.RibbonGeometry = RibbonGeometry;
  34038. /**
  34039. * Creates a box geometry
  34040. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  34041. */
  34042. var BoxGeometry = /** @class */ (function (_super) {
  34043. __extends(BoxGeometry, _super);
  34044. /**
  34045. * Creates a box geometry
  34046. * @param id defines the unique ID of the geometry
  34047. * @param scene defines the hosting scene
  34048. * @param size defines the zise of the box (width, height and depth are the same)
  34049. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34050. * @param mesh defines the hosting mesh (can be null)
  34051. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34052. */
  34053. function BoxGeometry(id, scene,
  34054. /**
  34055. * Defines the zise of the box (width, height and depth are the same)
  34056. */
  34057. size, canBeRegenerated, mesh,
  34058. /**
  34059. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34060. */
  34061. side) {
  34062. if (mesh === void 0) { mesh = null; }
  34063. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34064. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34065. _this.size = size;
  34066. _this.side = side;
  34067. return _this;
  34068. }
  34069. BoxGeometry.prototype._regenerateVertexData = function () {
  34070. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34071. };
  34072. BoxGeometry.prototype.copy = function (id) {
  34073. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  34074. };
  34075. BoxGeometry.prototype.serialize = function () {
  34076. var serializationObject = _super.prototype.serialize.call(this);
  34077. serializationObject.size = this.size;
  34078. return serializationObject;
  34079. };
  34080. BoxGeometry.Parse = function (parsedBox, scene) {
  34081. if (scene.getGeometryByID(parsedBox.id)) {
  34082. return null; // null since geometry could be something else than a box...
  34083. }
  34084. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34085. if (BABYLON.Tags) {
  34086. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34087. }
  34088. scene.pushGeometry(box, true);
  34089. return box;
  34090. };
  34091. return BoxGeometry;
  34092. }(_PrimitiveGeometry));
  34093. BABYLON.BoxGeometry = BoxGeometry;
  34094. /**
  34095. * Creates a sphere geometry
  34096. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  34097. */
  34098. var SphereGeometry = /** @class */ (function (_super) {
  34099. __extends(SphereGeometry, _super);
  34100. /**
  34101. * Create a new sphere geometry
  34102. * @param id defines the unique ID of the geometry
  34103. * @param scene defines the hosting scene
  34104. * @param segments defines the number of segments to use to create the sphere
  34105. * @param diameter defines the diameter of the sphere
  34106. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34107. * @param mesh defines the hosting mesh (can be null)
  34108. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34109. */
  34110. function SphereGeometry(id, scene,
  34111. /**
  34112. * Defines the number of segments to use to create the sphere
  34113. */
  34114. segments,
  34115. /**
  34116. * Defines the diameter of the sphere
  34117. */
  34118. diameter, canBeRegenerated, mesh,
  34119. /**
  34120. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34121. */
  34122. side) {
  34123. if (mesh === void 0) { mesh = null; }
  34124. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34125. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34126. _this.segments = segments;
  34127. _this.diameter = diameter;
  34128. _this.side = side;
  34129. return _this;
  34130. }
  34131. SphereGeometry.prototype._regenerateVertexData = function () {
  34132. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34133. };
  34134. SphereGeometry.prototype.copy = function (id) {
  34135. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34136. };
  34137. SphereGeometry.prototype.serialize = function () {
  34138. var serializationObject = _super.prototype.serialize.call(this);
  34139. serializationObject.segments = this.segments;
  34140. serializationObject.diameter = this.diameter;
  34141. return serializationObject;
  34142. };
  34143. SphereGeometry.Parse = function (parsedSphere, scene) {
  34144. if (scene.getGeometryByID(parsedSphere.id)) {
  34145. return null; // null since geometry could be something else than a sphere...
  34146. }
  34147. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34148. if (BABYLON.Tags) {
  34149. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34150. }
  34151. scene.pushGeometry(sphere, true);
  34152. return sphere;
  34153. };
  34154. return SphereGeometry;
  34155. }(_PrimitiveGeometry));
  34156. BABYLON.SphereGeometry = SphereGeometry;
  34157. /**
  34158. * Creates a disc geometry
  34159. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34160. */
  34161. var DiscGeometry = /** @class */ (function (_super) {
  34162. __extends(DiscGeometry, _super);
  34163. /**
  34164. * Creates a new disc geometry
  34165. * @param id defines the unique ID of the geometry
  34166. * @param scene defines the hosting scene
  34167. * @param radius defines the radius of the disc
  34168. * @param tessellation defines the tesselation factor to apply to the disc
  34169. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34170. * @param mesh defines the hosting mesh (can be null)
  34171. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34172. */
  34173. function DiscGeometry(id, scene,
  34174. /**
  34175. * Defines the radius of the disc
  34176. */
  34177. radius,
  34178. /**
  34179. * Defines the tesselation factor to apply to the disc
  34180. */
  34181. tessellation, canBeRegenerated, mesh,
  34182. /**
  34183. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34184. */
  34185. side) {
  34186. if (mesh === void 0) { mesh = null; }
  34187. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34188. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34189. _this.radius = radius;
  34190. _this.tessellation = tessellation;
  34191. _this.side = side;
  34192. return _this;
  34193. }
  34194. DiscGeometry.prototype._regenerateVertexData = function () {
  34195. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34196. };
  34197. DiscGeometry.prototype.copy = function (id) {
  34198. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34199. };
  34200. return DiscGeometry;
  34201. }(_PrimitiveGeometry));
  34202. BABYLON.DiscGeometry = DiscGeometry;
  34203. /**
  34204. * Creates a new cylinder geometry
  34205. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34206. */
  34207. var CylinderGeometry = /** @class */ (function (_super) {
  34208. __extends(CylinderGeometry, _super);
  34209. /**
  34210. * Creates a new cylinder geometry
  34211. * @param id defines the unique ID of the geometry
  34212. * @param scene defines the hosting scene
  34213. * @param height defines the height of the cylinder
  34214. * @param diameterTop defines the diameter of the cylinder's top cap
  34215. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34216. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34217. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34218. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34219. * @param mesh defines the hosting mesh (can be null)
  34220. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34221. */
  34222. function CylinderGeometry(id, scene,
  34223. /**
  34224. * Defines the height of the cylinder
  34225. */
  34226. height,
  34227. /**
  34228. * Defines the diameter of the cylinder's top cap
  34229. */
  34230. diameterTop,
  34231. /**
  34232. * Defines the diameter of the cylinder's bottom cap
  34233. */
  34234. diameterBottom,
  34235. /**
  34236. * Defines the tessellation factor to apply to the cylinder
  34237. */
  34238. tessellation,
  34239. /**
  34240. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34241. */
  34242. subdivisions, canBeRegenerated, mesh,
  34243. /**
  34244. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34245. */
  34246. side) {
  34247. if (subdivisions === void 0) { subdivisions = 1; }
  34248. if (mesh === void 0) { mesh = null; }
  34249. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34250. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34251. _this.height = height;
  34252. _this.diameterTop = diameterTop;
  34253. _this.diameterBottom = diameterBottom;
  34254. _this.tessellation = tessellation;
  34255. _this.subdivisions = subdivisions;
  34256. _this.side = side;
  34257. return _this;
  34258. }
  34259. CylinderGeometry.prototype._regenerateVertexData = function () {
  34260. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34261. };
  34262. CylinderGeometry.prototype.copy = function (id) {
  34263. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34264. };
  34265. CylinderGeometry.prototype.serialize = function () {
  34266. var serializationObject = _super.prototype.serialize.call(this);
  34267. serializationObject.height = this.height;
  34268. serializationObject.diameterTop = this.diameterTop;
  34269. serializationObject.diameterBottom = this.diameterBottom;
  34270. serializationObject.tessellation = this.tessellation;
  34271. return serializationObject;
  34272. };
  34273. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34274. if (scene.getGeometryByID(parsedCylinder.id)) {
  34275. return null; // null since geometry could be something else than a cylinder...
  34276. }
  34277. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34278. if (BABYLON.Tags) {
  34279. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34280. }
  34281. scene.pushGeometry(cylinder, true);
  34282. return cylinder;
  34283. };
  34284. return CylinderGeometry;
  34285. }(_PrimitiveGeometry));
  34286. BABYLON.CylinderGeometry = CylinderGeometry;
  34287. /**
  34288. * Creates a new torus geometry
  34289. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34290. */
  34291. var TorusGeometry = /** @class */ (function (_super) {
  34292. __extends(TorusGeometry, _super);
  34293. /**
  34294. * Creates a new torus geometry
  34295. * @param id defines the unique ID of the geometry
  34296. * @param scene defines the hosting scene
  34297. * @param diameter defines the diameter of the torus
  34298. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34299. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34300. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34301. * @param mesh defines the hosting mesh (can be null)
  34302. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34303. */
  34304. function TorusGeometry(id, scene,
  34305. /**
  34306. * Defines the diameter of the torus
  34307. */
  34308. diameter,
  34309. /**
  34310. * Defines the thickness of the torus (ie. internal diameter)
  34311. */
  34312. thickness,
  34313. /**
  34314. * Defines the tesselation factor to apply to the torus
  34315. */
  34316. tessellation, canBeRegenerated, mesh,
  34317. /**
  34318. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34319. */
  34320. side) {
  34321. if (mesh === void 0) { mesh = null; }
  34322. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34323. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34324. _this.diameter = diameter;
  34325. _this.thickness = thickness;
  34326. _this.tessellation = tessellation;
  34327. _this.side = side;
  34328. return _this;
  34329. }
  34330. TorusGeometry.prototype._regenerateVertexData = function () {
  34331. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34332. };
  34333. TorusGeometry.prototype.copy = function (id) {
  34334. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34335. };
  34336. TorusGeometry.prototype.serialize = function () {
  34337. var serializationObject = _super.prototype.serialize.call(this);
  34338. serializationObject.diameter = this.diameter;
  34339. serializationObject.thickness = this.thickness;
  34340. serializationObject.tessellation = this.tessellation;
  34341. return serializationObject;
  34342. };
  34343. TorusGeometry.Parse = function (parsedTorus, scene) {
  34344. if (scene.getGeometryByID(parsedTorus.id)) {
  34345. return null; // null since geometry could be something else than a torus...
  34346. }
  34347. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34348. if (BABYLON.Tags) {
  34349. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34350. }
  34351. scene.pushGeometry(torus, true);
  34352. return torus;
  34353. };
  34354. return TorusGeometry;
  34355. }(_PrimitiveGeometry));
  34356. BABYLON.TorusGeometry = TorusGeometry;
  34357. /**
  34358. * Creates a new ground geometry
  34359. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34360. */
  34361. var GroundGeometry = /** @class */ (function (_super) {
  34362. __extends(GroundGeometry, _super);
  34363. /**
  34364. * Creates a new ground geometry
  34365. * @param id defines the unique ID of the geometry
  34366. * @param scene defines the hosting scene
  34367. * @param width defines the width of the ground
  34368. * @param height defines the height of the ground
  34369. * @param subdivisions defines the subdivisions to apply to the ground
  34370. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34371. * @param mesh defines the hosting mesh (can be null)
  34372. */
  34373. function GroundGeometry(id, scene,
  34374. /**
  34375. * Defines the width of the ground
  34376. */
  34377. width,
  34378. /**
  34379. * Defines the height of the ground
  34380. */
  34381. height,
  34382. /**
  34383. * Defines the subdivisions to apply to the ground
  34384. */
  34385. subdivisions, canBeRegenerated, mesh) {
  34386. if (mesh === void 0) { mesh = null; }
  34387. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34388. _this.width = width;
  34389. _this.height = height;
  34390. _this.subdivisions = subdivisions;
  34391. return _this;
  34392. }
  34393. GroundGeometry.prototype._regenerateVertexData = function () {
  34394. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34395. };
  34396. GroundGeometry.prototype.copy = function (id) {
  34397. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34398. };
  34399. GroundGeometry.prototype.serialize = function () {
  34400. var serializationObject = _super.prototype.serialize.call(this);
  34401. serializationObject.width = this.width;
  34402. serializationObject.height = this.height;
  34403. serializationObject.subdivisions = this.subdivisions;
  34404. return serializationObject;
  34405. };
  34406. GroundGeometry.Parse = function (parsedGround, scene) {
  34407. if (scene.getGeometryByID(parsedGround.id)) {
  34408. return null; // null since geometry could be something else than a ground...
  34409. }
  34410. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34411. if (BABYLON.Tags) {
  34412. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34413. }
  34414. scene.pushGeometry(ground, true);
  34415. return ground;
  34416. };
  34417. return GroundGeometry;
  34418. }(_PrimitiveGeometry));
  34419. BABYLON.GroundGeometry = GroundGeometry;
  34420. /**
  34421. * Creates a tiled ground geometry
  34422. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34423. */
  34424. var TiledGroundGeometry = /** @class */ (function (_super) {
  34425. __extends(TiledGroundGeometry, _super);
  34426. /**
  34427. * Creates a tiled ground geometry
  34428. * @param id defines the unique ID of the geometry
  34429. * @param scene defines the hosting scene
  34430. * @param xmin defines the minimum value on X axis
  34431. * @param zmin defines the minimum value on Z axis
  34432. * @param xmax defines the maximum value on X axis
  34433. * @param zmax defines the maximum value on Z axis
  34434. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34435. * @param precision defines the precision to use when computing the tiles
  34436. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34437. * @param mesh defines the hosting mesh (can be null)
  34438. */
  34439. function TiledGroundGeometry(id, scene,
  34440. /**
  34441. * Defines the minimum value on X axis
  34442. */
  34443. xmin,
  34444. /**
  34445. * Defines the minimum value on Z axis
  34446. */
  34447. zmin,
  34448. /**
  34449. * Defines the maximum value on X axis
  34450. */
  34451. xmax,
  34452. /**
  34453. * Defines the maximum value on Z axis
  34454. */
  34455. zmax,
  34456. /**
  34457. * Defines the subdivisions to apply to the ground
  34458. */
  34459. subdivisions,
  34460. /**
  34461. * Defines the precision to use when computing the tiles
  34462. */
  34463. precision, canBeRegenerated, mesh) {
  34464. if (mesh === void 0) { mesh = null; }
  34465. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34466. _this.xmin = xmin;
  34467. _this.zmin = zmin;
  34468. _this.xmax = xmax;
  34469. _this.zmax = zmax;
  34470. _this.subdivisions = subdivisions;
  34471. _this.precision = precision;
  34472. return _this;
  34473. }
  34474. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34475. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34476. };
  34477. TiledGroundGeometry.prototype.copy = function (id) {
  34478. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34479. };
  34480. return TiledGroundGeometry;
  34481. }(_PrimitiveGeometry));
  34482. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34483. /**
  34484. * Creates a plane geometry
  34485. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34486. */
  34487. var PlaneGeometry = /** @class */ (function (_super) {
  34488. __extends(PlaneGeometry, _super);
  34489. /**
  34490. * Creates a plane geometry
  34491. * @param id defines the unique ID of the geometry
  34492. * @param scene defines the hosting scene
  34493. * @param size defines the size of the plane (width === height)
  34494. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34495. * @param mesh defines the hosting mesh (can be null)
  34496. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34497. */
  34498. function PlaneGeometry(id, scene,
  34499. /**
  34500. * Defines the size of the plane (width === height)
  34501. */
  34502. size, canBeRegenerated, mesh,
  34503. /**
  34504. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34505. */
  34506. side) {
  34507. if (mesh === void 0) { mesh = null; }
  34508. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34509. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34510. _this.size = size;
  34511. _this.side = side;
  34512. return _this;
  34513. }
  34514. PlaneGeometry.prototype._regenerateVertexData = function () {
  34515. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34516. };
  34517. PlaneGeometry.prototype.copy = function (id) {
  34518. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34519. };
  34520. PlaneGeometry.prototype.serialize = function () {
  34521. var serializationObject = _super.prototype.serialize.call(this);
  34522. serializationObject.size = this.size;
  34523. return serializationObject;
  34524. };
  34525. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34526. if (scene.getGeometryByID(parsedPlane.id)) {
  34527. return null; // null since geometry could be something else than a ground...
  34528. }
  34529. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34530. if (BABYLON.Tags) {
  34531. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34532. }
  34533. scene.pushGeometry(plane, true);
  34534. return plane;
  34535. };
  34536. return PlaneGeometry;
  34537. }(_PrimitiveGeometry));
  34538. BABYLON.PlaneGeometry = PlaneGeometry;
  34539. /**
  34540. * Creates a torus knot geometry
  34541. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34542. */
  34543. var TorusKnotGeometry = /** @class */ (function (_super) {
  34544. __extends(TorusKnotGeometry, _super);
  34545. /**
  34546. * Creates a torus knot geometry
  34547. * @param id defines the unique ID of the geometry
  34548. * @param scene defines the hosting scene
  34549. * @param radius defines the radius of the torus knot
  34550. * @param tube defines the thickness of the torus knot tube
  34551. * @param radialSegments defines the number of radial segments
  34552. * @param tubularSegments defines the number of tubular segments
  34553. * @param p defines the first number of windings
  34554. * @param q defines the second number of windings
  34555. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34556. * @param mesh defines the hosting mesh (can be null)
  34557. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34558. */
  34559. function TorusKnotGeometry(id, scene,
  34560. /**
  34561. * Defines the radius of the torus knot
  34562. */
  34563. radius,
  34564. /**
  34565. * Defines the thickness of the torus knot tube
  34566. */
  34567. tube,
  34568. /**
  34569. * Defines the number of radial segments
  34570. */
  34571. radialSegments,
  34572. /**
  34573. * Defines the number of tubular segments
  34574. */
  34575. tubularSegments,
  34576. /**
  34577. * Defines the first number of windings
  34578. */
  34579. p,
  34580. /**
  34581. * Defines the second number of windings
  34582. */
  34583. q, canBeRegenerated, mesh,
  34584. /**
  34585. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34586. */
  34587. side) {
  34588. if (mesh === void 0) { mesh = null; }
  34589. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34590. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34591. _this.radius = radius;
  34592. _this.tube = tube;
  34593. _this.radialSegments = radialSegments;
  34594. _this.tubularSegments = tubularSegments;
  34595. _this.p = p;
  34596. _this.q = q;
  34597. _this.side = side;
  34598. return _this;
  34599. }
  34600. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34601. 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 });
  34602. };
  34603. TorusKnotGeometry.prototype.copy = function (id) {
  34604. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34605. };
  34606. TorusKnotGeometry.prototype.serialize = function () {
  34607. var serializationObject = _super.prototype.serialize.call(this);
  34608. serializationObject.radius = this.radius;
  34609. serializationObject.tube = this.tube;
  34610. serializationObject.radialSegments = this.radialSegments;
  34611. serializationObject.tubularSegments = this.tubularSegments;
  34612. serializationObject.p = this.p;
  34613. serializationObject.q = this.q;
  34614. return serializationObject;
  34615. };
  34616. ;
  34617. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34618. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34619. return null; // null since geometry could be something else than a ground...
  34620. }
  34621. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34622. if (BABYLON.Tags) {
  34623. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34624. }
  34625. scene.pushGeometry(torusKnot, true);
  34626. return torusKnot;
  34627. };
  34628. return TorusKnotGeometry;
  34629. }(_PrimitiveGeometry));
  34630. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34631. //}
  34632. })(BABYLON || (BABYLON = {}));
  34633. //# sourceMappingURL=babylon.geometry.js.map
  34634. var BABYLON;
  34635. (function (BABYLON) {
  34636. /**
  34637. * PostProcessManager is used to manage one or more post processes or post process pipelines
  34638. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  34639. */
  34640. var PostProcessManager = /** @class */ (function () {
  34641. /**
  34642. * Creates a new instance of @see PostProcess
  34643. * @param scene The scene that the post process is associated with.
  34644. */
  34645. function PostProcessManager(scene) {
  34646. this._vertexBuffers = {};
  34647. this._scene = scene;
  34648. }
  34649. PostProcessManager.prototype._prepareBuffers = function () {
  34650. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34651. return;
  34652. }
  34653. // VBO
  34654. var vertices = [];
  34655. vertices.push(1, 1);
  34656. vertices.push(-1, 1);
  34657. vertices.push(-1, -1);
  34658. vertices.push(1, -1);
  34659. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34660. this._buildIndexBuffer();
  34661. };
  34662. PostProcessManager.prototype._buildIndexBuffer = function () {
  34663. // Indices
  34664. var indices = [];
  34665. indices.push(0);
  34666. indices.push(1);
  34667. indices.push(2);
  34668. indices.push(0);
  34669. indices.push(2);
  34670. indices.push(3);
  34671. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34672. };
  34673. /**
  34674. * Rebuilds the vertex buffers of the manager.
  34675. */
  34676. PostProcessManager.prototype._rebuild = function () {
  34677. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34678. if (!vb) {
  34679. return;
  34680. }
  34681. vb._rebuild();
  34682. this._buildIndexBuffer();
  34683. };
  34684. // Methods
  34685. /**
  34686. * Prepares a frame to be run through a post process.
  34687. * @param sourceTexture The input texture to the post procesess. (default: null)
  34688. * @param postProcesses An array of post processes to be run. (default: null)
  34689. * @returns True if the post processes were able to be run.
  34690. */
  34691. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34692. if (sourceTexture === void 0) { sourceTexture = null; }
  34693. if (postProcesses === void 0) { postProcesses = null; }
  34694. var camera = this._scene.activeCamera;
  34695. if (!camera) {
  34696. return false;
  34697. }
  34698. var postProcesses = postProcesses || camera._postProcesses;
  34699. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34700. return false;
  34701. }
  34702. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34703. return true;
  34704. };
  34705. /**
  34706. * Manually render a set of post processes to a texture.
  34707. * @param postProcesses An array of post processes to be run.
  34708. * @param targetTexture The target texture to render to.
  34709. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  34710. */
  34711. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34712. if (targetTexture === void 0) { targetTexture = null; }
  34713. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34714. var engine = this._scene.getEngine();
  34715. for (var index = 0; index < postProcesses.length; index++) {
  34716. if (index < postProcesses.length - 1) {
  34717. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34718. }
  34719. else {
  34720. if (targetTexture) {
  34721. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34722. }
  34723. else {
  34724. engine.restoreDefaultFramebuffer();
  34725. }
  34726. }
  34727. var pp = postProcesses[index];
  34728. var effect = pp.apply();
  34729. if (effect) {
  34730. pp.onBeforeRenderObservable.notifyObservers(effect);
  34731. // VBOs
  34732. this._prepareBuffers();
  34733. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34734. // Draw order
  34735. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34736. pp.onAfterRenderObservable.notifyObservers(effect);
  34737. }
  34738. }
  34739. // Restore depth buffer
  34740. engine.setDepthBuffer(true);
  34741. engine.setDepthWrite(true);
  34742. };
  34743. /**
  34744. * Finalize the result of the output of the postprocesses.
  34745. * @param doNotPresent If true the result will not be displayed to the screen.
  34746. * @param targetTexture The target texture to render to.
  34747. * @param faceIndex The index of the face to bind the target texture to.
  34748. * @param postProcesses The array of post processes to render.
  34749. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  34750. */
  34751. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34752. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34753. var camera = this._scene.activeCamera;
  34754. if (!camera) {
  34755. return;
  34756. }
  34757. postProcesses = postProcesses || camera._postProcesses;
  34758. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34759. return;
  34760. }
  34761. var engine = this._scene.getEngine();
  34762. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34763. if (index < len - 1) {
  34764. postProcesses[index + 1].activate(camera, targetTexture);
  34765. }
  34766. else {
  34767. if (targetTexture) {
  34768. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34769. }
  34770. else {
  34771. engine.restoreDefaultFramebuffer();
  34772. }
  34773. }
  34774. if (doNotPresent) {
  34775. break;
  34776. }
  34777. var pp = postProcesses[index];
  34778. var effect = pp.apply();
  34779. if (effect) {
  34780. pp.onBeforeRenderObservable.notifyObservers(effect);
  34781. // VBOs
  34782. this._prepareBuffers();
  34783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34784. // Draw order
  34785. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34786. pp.onAfterRenderObservable.notifyObservers(effect);
  34787. }
  34788. }
  34789. // Restore states
  34790. engine.setDepthBuffer(true);
  34791. engine.setDepthWrite(true);
  34792. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34793. };
  34794. /**
  34795. * Disposes of the post process manager.
  34796. */
  34797. PostProcessManager.prototype.dispose = function () {
  34798. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34799. if (buffer) {
  34800. buffer.dispose();
  34801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34802. }
  34803. if (this._indexBuffer) {
  34804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34805. this._indexBuffer = null;
  34806. }
  34807. };
  34808. return PostProcessManager;
  34809. }());
  34810. BABYLON.PostProcessManager = PostProcessManager;
  34811. })(BABYLON || (BABYLON = {}));
  34812. //# sourceMappingURL=babylon.postProcessManager.js.map
  34813. var BABYLON;
  34814. (function (BABYLON) {
  34815. /**
  34816. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34817. */
  34818. var PerformanceMonitor = /** @class */ (function () {
  34819. /**
  34820. * constructor
  34821. * @param frameSampleSize The number of samples required to saturate the sliding window
  34822. */
  34823. function PerformanceMonitor(frameSampleSize) {
  34824. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34825. this._enabled = true;
  34826. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34827. }
  34828. /**
  34829. * Samples current frame
  34830. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34831. */
  34832. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34833. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34834. if (!this._enabled)
  34835. return;
  34836. if (this._lastFrameTimeMs != null) {
  34837. var dt = timeMs - this._lastFrameTimeMs;
  34838. this._rollingFrameTime.add(dt);
  34839. }
  34840. this._lastFrameTimeMs = timeMs;
  34841. };
  34842. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34843. /**
  34844. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34845. * @return Average frame time in milliseconds
  34846. */
  34847. get: function () {
  34848. return this._rollingFrameTime.average;
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34854. /**
  34855. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34856. * @return Frame time variance in milliseconds squared
  34857. */
  34858. get: function () {
  34859. return this._rollingFrameTime.variance;
  34860. },
  34861. enumerable: true,
  34862. configurable: true
  34863. });
  34864. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34865. /**
  34866. * Returns the frame time of the most recent frame
  34867. * @return Frame time in milliseconds
  34868. */
  34869. get: function () {
  34870. return this._rollingFrameTime.history(0);
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34876. /**
  34877. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34878. * @return Framerate in frames per second
  34879. */
  34880. get: function () {
  34881. return 1000.0 / this._rollingFrameTime.average;
  34882. },
  34883. enumerable: true,
  34884. configurable: true
  34885. });
  34886. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34887. /**
  34888. * Returns the average framerate in frames per second using the most recent frame time
  34889. * @return Framerate in frames per second
  34890. */
  34891. get: function () {
  34892. var history = this._rollingFrameTime.history(0);
  34893. if (history === 0) {
  34894. return 0;
  34895. }
  34896. return 1000.0 / history;
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34902. /**
  34903. * Returns true if enough samples have been taken to completely fill the sliding window
  34904. * @return true if saturated
  34905. */
  34906. get: function () {
  34907. return this._rollingFrameTime.isSaturated();
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. /**
  34913. * Enables contributions to the sliding window sample set
  34914. */
  34915. PerformanceMonitor.prototype.enable = function () {
  34916. this._enabled = true;
  34917. };
  34918. /**
  34919. * Disables contributions to the sliding window sample set
  34920. * Samples will not be interpolated over the disabled period
  34921. */
  34922. PerformanceMonitor.prototype.disable = function () {
  34923. this._enabled = false;
  34924. //clear last sample to avoid interpolating over the disabled period when next enabled
  34925. this._lastFrameTimeMs = null;
  34926. };
  34927. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34928. /**
  34929. * Returns true if sampling is enabled
  34930. * @return true if enabled
  34931. */
  34932. get: function () {
  34933. return this._enabled;
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. /**
  34939. * Resets performance monitor
  34940. */
  34941. PerformanceMonitor.prototype.reset = function () {
  34942. //clear last sample to avoid interpolating over the disabled period when next enabled
  34943. this._lastFrameTimeMs = null;
  34944. //wipe record
  34945. this._rollingFrameTime.reset();
  34946. };
  34947. return PerformanceMonitor;
  34948. }());
  34949. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34950. /**
  34951. * RollingAverage
  34952. *
  34953. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34954. */
  34955. var RollingAverage = /** @class */ (function () {
  34956. /**
  34957. * constructor
  34958. * @param length The number of samples required to saturate the sliding window
  34959. */
  34960. function RollingAverage(length) {
  34961. this._samples = new Array(length);
  34962. this.reset();
  34963. }
  34964. /**
  34965. * Adds a sample to the sample set
  34966. * @param v The sample value
  34967. */
  34968. RollingAverage.prototype.add = function (v) {
  34969. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34970. var delta;
  34971. //we need to check if we've already wrapped round
  34972. if (this.isSaturated()) {
  34973. //remove bottom of stack from mean
  34974. var bottomValue = this._samples[this._pos];
  34975. delta = bottomValue - this.average;
  34976. this.average -= delta / (this._sampleCount - 1);
  34977. this._m2 -= delta * (bottomValue - this.average);
  34978. }
  34979. else {
  34980. this._sampleCount++;
  34981. }
  34982. //add new value to mean
  34983. delta = v - this.average;
  34984. this.average += delta / (this._sampleCount);
  34985. this._m2 += delta * (v - this.average);
  34986. //set the new variance
  34987. this.variance = this._m2 / (this._sampleCount - 1);
  34988. this._samples[this._pos] = v;
  34989. this._pos++;
  34990. this._pos %= this._samples.length; //positive wrap around
  34991. };
  34992. /**
  34993. * Returns previously added values or null if outside of history or outside the sliding window domain
  34994. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34995. * @return Value previously recorded with add() or null if outside of range
  34996. */
  34997. RollingAverage.prototype.history = function (i) {
  34998. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34999. return 0;
  35000. }
  35001. var i0 = this._wrapPosition(this._pos - 1.0);
  35002. return this._samples[this._wrapPosition(i0 - i)];
  35003. };
  35004. /**
  35005. * Returns true if enough samples have been taken to completely fill the sliding window
  35006. * @return true if sample-set saturated
  35007. */
  35008. RollingAverage.prototype.isSaturated = function () {
  35009. return this._sampleCount >= this._samples.length;
  35010. };
  35011. /**
  35012. * Resets the rolling average (equivalent to 0 samples taken so far)
  35013. */
  35014. RollingAverage.prototype.reset = function () {
  35015. this.average = 0;
  35016. this.variance = 0;
  35017. this._sampleCount = 0;
  35018. this._pos = 0;
  35019. this._m2 = 0;
  35020. };
  35021. /**
  35022. * Wraps a value around the sample range boundaries
  35023. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  35024. * @return Wrapped position in sample range
  35025. */
  35026. RollingAverage.prototype._wrapPosition = function (i) {
  35027. var max = this._samples.length;
  35028. return ((i % max) + max) % max;
  35029. };
  35030. return RollingAverage;
  35031. }());
  35032. BABYLON.RollingAverage = RollingAverage;
  35033. })(BABYLON || (BABYLON = {}));
  35034. //# sourceMappingURL=babylon.performanceMonitor.js.map
  35035. var BABYLON;
  35036. (function (BABYLON) {
  35037. /**
  35038. * This groups together the common properties used for image processing either in direct forward pass
  35039. * or through post processing effect depending on the use of the image processing pipeline in your scene
  35040. * or not.
  35041. */
  35042. var ImageProcessingConfiguration = /** @class */ (function () {
  35043. function ImageProcessingConfiguration() {
  35044. /**
  35045. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  35046. */
  35047. this.colorCurves = new BABYLON.ColorCurves();
  35048. this._colorCurvesEnabled = false;
  35049. this._colorGradingEnabled = false;
  35050. this._colorGradingWithGreenDepth = true;
  35051. this._colorGradingBGR = true;
  35052. this._exposure = 1.0;
  35053. this._toneMappingEnabled = false;
  35054. this._contrast = 1.0;
  35055. /**
  35056. * Vignette stretch size.
  35057. */
  35058. this.vignetteStretch = 0;
  35059. /**
  35060. * Vignette centre X Offset.
  35061. */
  35062. this.vignetteCentreX = 0;
  35063. /**
  35064. * Vignette centre Y Offset.
  35065. */
  35066. this.vignetteCentreY = 0;
  35067. /**
  35068. * Vignette weight or intensity of the vignette effect.
  35069. */
  35070. this.vignetteWeight = 1.5;
  35071. /**
  35072. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  35073. * if vignetteEnabled is set to true.
  35074. */
  35075. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  35076. /**
  35077. * Camera field of view used by the Vignette effect.
  35078. */
  35079. this.vignetteCameraFov = 0.5;
  35080. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  35081. this._vignetteEnabled = false;
  35082. this._applyByPostProcess = false;
  35083. this._isEnabled = true;
  35084. /**
  35085. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  35086. * @type {BABYLON.Observable}
  35087. */
  35088. this.onUpdateParameters = new BABYLON.Observable();
  35089. }
  35090. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  35091. /**
  35092. * Gets wether the color curves effect is enabled.
  35093. */
  35094. get: function () {
  35095. return this._colorCurvesEnabled;
  35096. },
  35097. /**
  35098. * Sets wether the color curves effect is enabled.
  35099. */
  35100. set: function (value) {
  35101. if (this._colorCurvesEnabled === value) {
  35102. return;
  35103. }
  35104. this._colorCurvesEnabled = value;
  35105. this._updateParameters();
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  35111. /**
  35112. * Gets wether the color grading effect is enabled.
  35113. */
  35114. get: function () {
  35115. return this._colorGradingEnabled;
  35116. },
  35117. /**
  35118. * Sets wether the color grading effect is enabled.
  35119. */
  35120. set: function (value) {
  35121. if (this._colorGradingEnabled === value) {
  35122. return;
  35123. }
  35124. this._colorGradingEnabled = value;
  35125. this._updateParameters();
  35126. },
  35127. enumerable: true,
  35128. configurable: true
  35129. });
  35130. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  35131. /**
  35132. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  35133. */
  35134. get: function () {
  35135. return this._colorGradingWithGreenDepth;
  35136. },
  35137. /**
  35138. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  35139. */
  35140. set: function (value) {
  35141. if (this._colorGradingWithGreenDepth === value) {
  35142. return;
  35143. }
  35144. this._colorGradingWithGreenDepth = value;
  35145. this._updateParameters();
  35146. },
  35147. enumerable: true,
  35148. configurable: true
  35149. });
  35150. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  35151. /**
  35152. * Gets wether the color grading texture contains BGR values.
  35153. */
  35154. get: function () {
  35155. return this._colorGradingBGR;
  35156. },
  35157. /**
  35158. * Sets wether the color grading texture contains BGR values.
  35159. */
  35160. set: function (value) {
  35161. if (this._colorGradingBGR === value) {
  35162. return;
  35163. }
  35164. this._colorGradingBGR = value;
  35165. this._updateParameters();
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  35171. /**
  35172. * Gets the Exposure used in the effect.
  35173. */
  35174. get: function () {
  35175. return this._exposure;
  35176. },
  35177. /**
  35178. * Sets the Exposure used in the effect.
  35179. */
  35180. set: function (value) {
  35181. if (this._exposure === value) {
  35182. return;
  35183. }
  35184. this._exposure = value;
  35185. this._updateParameters();
  35186. },
  35187. enumerable: true,
  35188. configurable: true
  35189. });
  35190. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35191. /**
  35192. * Gets wether the tone mapping effect is enabled.
  35193. */
  35194. get: function () {
  35195. return this._toneMappingEnabled;
  35196. },
  35197. /**
  35198. * Sets wether the tone mapping effect is enabled.
  35199. */
  35200. set: function (value) {
  35201. if (this._toneMappingEnabled === value) {
  35202. return;
  35203. }
  35204. this._toneMappingEnabled = value;
  35205. this._updateParameters();
  35206. },
  35207. enumerable: true,
  35208. configurable: true
  35209. });
  35210. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35211. /**
  35212. * Gets the contrast used in the effect.
  35213. */
  35214. get: function () {
  35215. return this._contrast;
  35216. },
  35217. /**
  35218. * Sets the contrast used in the effect.
  35219. */
  35220. set: function (value) {
  35221. if (this._contrast === value) {
  35222. return;
  35223. }
  35224. this._contrast = value;
  35225. this._updateParameters();
  35226. },
  35227. enumerable: true,
  35228. configurable: true
  35229. });
  35230. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35231. /**
  35232. * Gets the vignette blend mode allowing different kind of effect.
  35233. */
  35234. get: function () {
  35235. return this._vignetteBlendMode;
  35236. },
  35237. /**
  35238. * Sets the vignette blend mode allowing different kind of effect.
  35239. */
  35240. set: function (value) {
  35241. if (this._vignetteBlendMode === value) {
  35242. return;
  35243. }
  35244. this._vignetteBlendMode = value;
  35245. this._updateParameters();
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35251. /**
  35252. * Gets wether the vignette effect is enabled.
  35253. */
  35254. get: function () {
  35255. return this._vignetteEnabled;
  35256. },
  35257. /**
  35258. * Sets wether the vignette effect is enabled.
  35259. */
  35260. set: function (value) {
  35261. if (this._vignetteEnabled === value) {
  35262. return;
  35263. }
  35264. this._vignetteEnabled = value;
  35265. this._updateParameters();
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35271. /**
  35272. * Gets wether the image processing is applied through a post process or not.
  35273. */
  35274. get: function () {
  35275. return this._applyByPostProcess;
  35276. },
  35277. /**
  35278. * Sets wether the image processing is applied through a post process or not.
  35279. */
  35280. set: function (value) {
  35281. if (this._applyByPostProcess === value) {
  35282. return;
  35283. }
  35284. this._applyByPostProcess = value;
  35285. this._updateParameters();
  35286. },
  35287. enumerable: true,
  35288. configurable: true
  35289. });
  35290. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35291. /**
  35292. * Gets wether the image processing is enabled or not.
  35293. */
  35294. get: function () {
  35295. return this._isEnabled;
  35296. },
  35297. /**
  35298. * Sets wether the image processing is enabled or not.
  35299. */
  35300. set: function (value) {
  35301. if (this._isEnabled === value) {
  35302. return;
  35303. }
  35304. this._isEnabled = value;
  35305. this._updateParameters();
  35306. },
  35307. enumerable: true,
  35308. configurable: true
  35309. });
  35310. /**
  35311. * Method called each time the image processing information changes requires to recompile the effect.
  35312. */
  35313. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35314. this.onUpdateParameters.notifyObservers(this);
  35315. };
  35316. ImageProcessingConfiguration.prototype.getClassName = function () {
  35317. return "ImageProcessingConfiguration";
  35318. };
  35319. /**
  35320. * Prepare the list of uniforms associated with the Image Processing effects.
  35321. * @param uniformsList The list of uniforms used in the effect
  35322. * @param defines the list of defines currently in use
  35323. */
  35324. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35325. if (defines.EXPOSURE) {
  35326. uniforms.push("exposureLinear");
  35327. }
  35328. if (defines.CONTRAST) {
  35329. uniforms.push("contrast");
  35330. }
  35331. if (defines.COLORGRADING) {
  35332. uniforms.push("colorTransformSettings");
  35333. }
  35334. if (defines.VIGNETTE) {
  35335. uniforms.push("vInverseScreenSize");
  35336. uniforms.push("vignetteSettings1");
  35337. uniforms.push("vignetteSettings2");
  35338. }
  35339. if (defines.COLORCURVES) {
  35340. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35341. }
  35342. };
  35343. /**
  35344. * Prepare the list of samplers associated with the Image Processing effects.
  35345. * @param uniformsList The list of uniforms used in the effect
  35346. * @param defines the list of defines currently in use
  35347. */
  35348. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35349. if (defines.COLORGRADING) {
  35350. samplersList.push("txColorTransform");
  35351. }
  35352. };
  35353. /**
  35354. * Prepare the list of defines associated to the shader.
  35355. * @param defines the list of defines to complete
  35356. */
  35357. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35358. if (forPostProcess === void 0) { forPostProcess = false; }
  35359. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35360. defines.VIGNETTE = false;
  35361. defines.TONEMAPPING = false;
  35362. defines.CONTRAST = false;
  35363. defines.EXPOSURE = false;
  35364. defines.COLORCURVES = false;
  35365. defines.COLORGRADING = false;
  35366. defines.COLORGRADING3D = false;
  35367. defines.IMAGEPROCESSING = false;
  35368. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35369. return;
  35370. }
  35371. defines.VIGNETTE = this.vignetteEnabled;
  35372. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35373. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35374. defines.TONEMAPPING = this.toneMappingEnabled;
  35375. defines.CONTRAST = (this.contrast !== 1.0);
  35376. defines.EXPOSURE = (this.exposure !== 1.0);
  35377. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35378. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35379. if (defines.COLORGRADING) {
  35380. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35381. }
  35382. else {
  35383. defines.COLORGRADING3D = false;
  35384. }
  35385. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35386. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35387. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35388. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35389. };
  35390. /**
  35391. * Returns true if all the image processing information are ready.
  35392. */
  35393. ImageProcessingConfiguration.prototype.isReady = function () {
  35394. // Color Grading texure can not be none blocking.
  35395. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35396. };
  35397. /**
  35398. * Binds the image processing to the shader.
  35399. * @param effect The effect to bind to
  35400. */
  35401. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35402. if (aspectRatio === void 0) { aspectRatio = 1; }
  35403. // Color Curves
  35404. if (this._colorCurvesEnabled && this.colorCurves) {
  35405. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35406. }
  35407. // Vignette
  35408. if (this._vignetteEnabled) {
  35409. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35410. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35411. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35412. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35413. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35414. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35415. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35416. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35417. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35418. var vignettePower = -2.0 * this.vignetteWeight;
  35419. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35420. }
  35421. // Exposure
  35422. effect.setFloat("exposureLinear", this.exposure);
  35423. // Contrast
  35424. effect.setFloat("contrast", this.contrast);
  35425. // Color transform settings
  35426. if (this.colorGradingTexture) {
  35427. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35428. var textureSize = this.colorGradingTexture.getSize().height;
  35429. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35430. 0.5 / textureSize, // textureOffset
  35431. textureSize, // textureSize
  35432. this.colorGradingTexture.level // weight
  35433. );
  35434. }
  35435. };
  35436. /**
  35437. * Clones the current image processing instance.
  35438. * @return The cloned image processing
  35439. */
  35440. ImageProcessingConfiguration.prototype.clone = function () {
  35441. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35442. };
  35443. /**
  35444. * Serializes the current image processing instance to a json representation.
  35445. * @return a JSON representation
  35446. */
  35447. ImageProcessingConfiguration.prototype.serialize = function () {
  35448. return BABYLON.SerializationHelper.Serialize(this);
  35449. };
  35450. /**
  35451. * Parses the image processing from a json representation.
  35452. * @param source the JSON source to parse
  35453. * @return The parsed image processing
  35454. */
  35455. ImageProcessingConfiguration.Parse = function (source) {
  35456. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35457. };
  35458. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35459. /**
  35460. * Used to apply the vignette as a mix with the pixel color.
  35461. */
  35462. get: function () {
  35463. return this._VIGNETTEMODE_MULTIPLY;
  35464. },
  35465. enumerable: true,
  35466. configurable: true
  35467. });
  35468. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35469. /**
  35470. * Used to apply the vignette as a replacement of the pixel color.
  35471. */
  35472. get: function () {
  35473. return this._VIGNETTEMODE_OPAQUE;
  35474. },
  35475. enumerable: true,
  35476. configurable: true
  35477. });
  35478. // Static constants associated to the image processing.
  35479. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35480. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35481. __decorate([
  35482. BABYLON.serializeAsColorCurves()
  35483. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35484. __decorate([
  35485. BABYLON.serialize()
  35486. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35487. __decorate([
  35488. BABYLON.serializeAsTexture()
  35489. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35490. __decorate([
  35491. BABYLON.serialize()
  35492. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35493. __decorate([
  35494. BABYLON.serialize()
  35495. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35496. __decorate([
  35497. BABYLON.serialize()
  35498. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35499. __decorate([
  35500. BABYLON.serialize()
  35501. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35502. __decorate([
  35503. BABYLON.serialize()
  35504. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35505. __decorate([
  35506. BABYLON.serialize()
  35507. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35508. __decorate([
  35509. BABYLON.serialize()
  35510. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35511. __decorate([
  35512. BABYLON.serialize()
  35513. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35514. __decorate([
  35515. BABYLON.serialize()
  35516. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35517. __decorate([
  35518. BABYLON.serialize()
  35519. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35520. __decorate([
  35521. BABYLON.serializeAsColor4()
  35522. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35523. __decorate([
  35524. BABYLON.serialize()
  35525. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35526. __decorate([
  35527. BABYLON.serialize()
  35528. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35529. __decorate([
  35530. BABYLON.serialize()
  35531. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35532. __decorate([
  35533. BABYLON.serialize()
  35534. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35535. __decorate([
  35536. BABYLON.serialize()
  35537. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35538. return ImageProcessingConfiguration;
  35539. }());
  35540. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35541. })(BABYLON || (BABYLON = {}));
  35542. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35543. var BABYLON;
  35544. (function (BABYLON) {
  35545. /**
  35546. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35547. * It can help converting any input color in a desired output one. This can then be used to create effects
  35548. * from sepia, black and white to sixties or futuristic rendering...
  35549. *
  35550. * The only supported format is currently 3dl.
  35551. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35552. */
  35553. var ColorGradingTexture = /** @class */ (function (_super) {
  35554. __extends(ColorGradingTexture, _super);
  35555. /**
  35556. * Instantiates a ColorGradingTexture from the following parameters.
  35557. *
  35558. * @param url The location of the color gradind data (currently only supporting 3dl)
  35559. * @param scene The scene the texture will be used in
  35560. */
  35561. function ColorGradingTexture(url, scene) {
  35562. var _this = _super.call(this, scene) || this;
  35563. if (!url) {
  35564. return _this;
  35565. }
  35566. _this._engine = scene.getEngine();
  35567. _this._textureMatrix = BABYLON.Matrix.Identity();
  35568. _this.name = url;
  35569. _this.url = url;
  35570. _this.hasAlpha = false;
  35571. _this.isCube = false;
  35572. _this.is3D = _this._engine.webGLVersion > 1;
  35573. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35574. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35575. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35576. _this.anisotropicFilteringLevel = 1;
  35577. _this._texture = _this._getFromCache(url, true);
  35578. if (!_this._texture) {
  35579. if (!scene.useDelayedTextureLoading) {
  35580. _this.loadTexture();
  35581. }
  35582. else {
  35583. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35584. }
  35585. }
  35586. return _this;
  35587. }
  35588. /**
  35589. * Returns the texture matrix used in most of the material.
  35590. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35591. */
  35592. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35593. return this._textureMatrix;
  35594. };
  35595. /**
  35596. * Occurs when the file being loaded is a .3dl LUT file.
  35597. */
  35598. ColorGradingTexture.prototype.load3dlTexture = function () {
  35599. var engine = this._engine;
  35600. var texture;
  35601. if (engine.webGLVersion === 1) {
  35602. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35603. }
  35604. else {
  35605. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35606. }
  35607. this._texture = texture;
  35608. var callback = function (text) {
  35609. if (typeof text !== "string") {
  35610. return;
  35611. }
  35612. var data = null;
  35613. var tempData = null;
  35614. var line;
  35615. var lines = text.split('\n');
  35616. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35617. var maxColor = 0;
  35618. for (var i = 0; i < lines.length; i++) {
  35619. line = lines[i];
  35620. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35621. continue;
  35622. if (line.indexOf('#') === 0)
  35623. continue;
  35624. var words = line.split(" ");
  35625. if (size === 0) {
  35626. // Number of space + one
  35627. size = words.length;
  35628. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35629. tempData = new Float32Array(size * size * size * 4);
  35630. continue;
  35631. }
  35632. if (size != 0) {
  35633. var r = Math.max(parseInt(words[0]), 0);
  35634. var g = Math.max(parseInt(words[1]), 0);
  35635. var b = Math.max(parseInt(words[2]), 0);
  35636. maxColor = Math.max(r, maxColor);
  35637. maxColor = Math.max(g, maxColor);
  35638. maxColor = Math.max(b, maxColor);
  35639. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35640. if (tempData) {
  35641. tempData[pixelStorageIndex + 0] = r;
  35642. tempData[pixelStorageIndex + 1] = g;
  35643. tempData[pixelStorageIndex + 2] = b;
  35644. }
  35645. pixelIndexSlice++;
  35646. if (pixelIndexSlice % size == 0) {
  35647. pixelIndexH++;
  35648. pixelIndexSlice = 0;
  35649. if (pixelIndexH % size == 0) {
  35650. pixelIndexW++;
  35651. pixelIndexH = 0;
  35652. }
  35653. }
  35654. }
  35655. }
  35656. if (tempData && data) {
  35657. for (var i = 0; i < tempData.length; i++) {
  35658. if (i > 0 && (i + 1) % 4 === 0) {
  35659. data[i] = 255;
  35660. }
  35661. else {
  35662. var value = tempData[i];
  35663. data[i] = (value / maxColor * 255);
  35664. }
  35665. }
  35666. }
  35667. if (texture.is3D) {
  35668. texture.updateSize(size, size, size);
  35669. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35670. }
  35671. else {
  35672. texture.updateSize(size * size, size);
  35673. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35674. }
  35675. };
  35676. var scene = this.getScene();
  35677. if (scene) {
  35678. scene._loadFile(this.url, callback);
  35679. }
  35680. else {
  35681. this._engine._loadFile(this.url, callback);
  35682. }
  35683. return this._texture;
  35684. };
  35685. /**
  35686. * Starts the loading process of the texture.
  35687. */
  35688. ColorGradingTexture.prototype.loadTexture = function () {
  35689. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35690. this.load3dlTexture();
  35691. }
  35692. };
  35693. /**
  35694. * Clones the color gradind texture.
  35695. */
  35696. ColorGradingTexture.prototype.clone = function () {
  35697. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35698. // Base texture
  35699. newTexture.level = this.level;
  35700. return newTexture;
  35701. };
  35702. /**
  35703. * Called during delayed load for textures.
  35704. */
  35705. ColorGradingTexture.prototype.delayLoad = function () {
  35706. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35707. return;
  35708. }
  35709. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35710. this._texture = this._getFromCache(this.url, true);
  35711. if (!this._texture) {
  35712. this.loadTexture();
  35713. }
  35714. };
  35715. /**
  35716. * Parses a color grading texture serialized by Babylon.
  35717. * @param parsedTexture The texture information being parsedTexture
  35718. * @param scene The scene to load the texture in
  35719. * @param rootUrl The root url of the data assets to load
  35720. * @return A color gradind texture
  35721. */
  35722. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35723. var texture = null;
  35724. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35725. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35726. texture.name = parsedTexture.name;
  35727. texture.level = parsedTexture.level;
  35728. }
  35729. return texture;
  35730. };
  35731. /**
  35732. * Serializes the LUT texture to json format.
  35733. */
  35734. ColorGradingTexture.prototype.serialize = function () {
  35735. if (!this.name) {
  35736. return null;
  35737. }
  35738. var serializationObject = {};
  35739. serializationObject.name = this.name;
  35740. serializationObject.level = this.level;
  35741. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35742. return serializationObject;
  35743. };
  35744. /**
  35745. * Empty line regex stored for GC.
  35746. */
  35747. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35748. return ColorGradingTexture;
  35749. }(BABYLON.BaseTexture));
  35750. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35751. })(BABYLON || (BABYLON = {}));
  35752. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35753. var BABYLON;
  35754. (function (BABYLON) {
  35755. /**
  35756. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35757. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35758. * 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;
  35759. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35760. */
  35761. var ColorCurves = /** @class */ (function () {
  35762. function ColorCurves() {
  35763. this._dirty = true;
  35764. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35765. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35766. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35767. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35768. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35769. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35770. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35771. this._globalHue = 30;
  35772. this._globalDensity = 0;
  35773. this._globalSaturation = 0;
  35774. this._globalExposure = 0;
  35775. this._highlightsHue = 30;
  35776. this._highlightsDensity = 0;
  35777. this._highlightsSaturation = 0;
  35778. this._highlightsExposure = 0;
  35779. this._midtonesHue = 30;
  35780. this._midtonesDensity = 0;
  35781. this._midtonesSaturation = 0;
  35782. this._midtonesExposure = 0;
  35783. this._shadowsHue = 30;
  35784. this._shadowsDensity = 0;
  35785. this._shadowsSaturation = 0;
  35786. this._shadowsExposure = 0;
  35787. }
  35788. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35789. /**
  35790. * Gets the global Hue value.
  35791. * 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).
  35792. */
  35793. get: function () {
  35794. return this._globalHue;
  35795. },
  35796. /**
  35797. * Sets the global Hue value.
  35798. * 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).
  35799. */
  35800. set: function (value) {
  35801. this._globalHue = value;
  35802. this._dirty = true;
  35803. },
  35804. enumerable: true,
  35805. configurable: true
  35806. });
  35807. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35808. /**
  35809. * Gets the global Density value.
  35810. * 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.
  35811. * Values less than zero provide a filter of opposite hue.
  35812. */
  35813. get: function () {
  35814. return this._globalDensity;
  35815. },
  35816. /**
  35817. * Sets the global Density value.
  35818. * 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.
  35819. * Values less than zero provide a filter of opposite hue.
  35820. */
  35821. set: function (value) {
  35822. this._globalDensity = value;
  35823. this._dirty = true;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35829. /**
  35830. * Gets the global Saturation value.
  35831. * 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.
  35832. */
  35833. get: function () {
  35834. return this._globalSaturation;
  35835. },
  35836. /**
  35837. * Sets the global Saturation value.
  35838. * 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.
  35839. */
  35840. set: function (value) {
  35841. this._globalSaturation = value;
  35842. this._dirty = true;
  35843. },
  35844. enumerable: true,
  35845. configurable: true
  35846. });
  35847. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35848. /**
  35849. * Gets the highlights Hue value.
  35850. * 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).
  35851. */
  35852. get: function () {
  35853. return this._highlightsHue;
  35854. },
  35855. /**
  35856. * Sets the highlights Hue value.
  35857. * 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).
  35858. */
  35859. set: function (value) {
  35860. this._highlightsHue = value;
  35861. this._dirty = true;
  35862. },
  35863. enumerable: true,
  35864. configurable: true
  35865. });
  35866. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35867. /**
  35868. * Gets the highlights Density value.
  35869. * 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.
  35870. * Values less than zero provide a filter of opposite hue.
  35871. */
  35872. get: function () {
  35873. return this._highlightsDensity;
  35874. },
  35875. /**
  35876. * Sets the highlights Density value.
  35877. * 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.
  35878. * Values less than zero provide a filter of opposite hue.
  35879. */
  35880. set: function (value) {
  35881. this._highlightsDensity = value;
  35882. this._dirty = true;
  35883. },
  35884. enumerable: true,
  35885. configurable: true
  35886. });
  35887. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35888. /**
  35889. * Gets the highlights Saturation value.
  35890. * 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.
  35891. */
  35892. get: function () {
  35893. return this._highlightsSaturation;
  35894. },
  35895. /**
  35896. * Sets the highlights Saturation value.
  35897. * 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.
  35898. */
  35899. set: function (value) {
  35900. this._highlightsSaturation = value;
  35901. this._dirty = true;
  35902. },
  35903. enumerable: true,
  35904. configurable: true
  35905. });
  35906. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35907. /**
  35908. * Gets the highlights Exposure value.
  35909. * 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.
  35910. */
  35911. get: function () {
  35912. return this._highlightsExposure;
  35913. },
  35914. /**
  35915. * Sets the highlights Exposure value.
  35916. * 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.
  35917. */
  35918. set: function (value) {
  35919. this._highlightsExposure = value;
  35920. this._dirty = true;
  35921. },
  35922. enumerable: true,
  35923. configurable: true
  35924. });
  35925. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35926. /**
  35927. * Gets the midtones Hue value.
  35928. * 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).
  35929. */
  35930. get: function () {
  35931. return this._midtonesHue;
  35932. },
  35933. /**
  35934. * Sets the midtones Hue value.
  35935. * 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).
  35936. */
  35937. set: function (value) {
  35938. this._midtonesHue = value;
  35939. this._dirty = true;
  35940. },
  35941. enumerable: true,
  35942. configurable: true
  35943. });
  35944. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35945. /**
  35946. * Gets the midtones Density value.
  35947. * 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.
  35948. * Values less than zero provide a filter of opposite hue.
  35949. */
  35950. get: function () {
  35951. return this._midtonesDensity;
  35952. },
  35953. /**
  35954. * Sets the midtones Density value.
  35955. * 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.
  35956. * Values less than zero provide a filter of opposite hue.
  35957. */
  35958. set: function (value) {
  35959. this._midtonesDensity = value;
  35960. this._dirty = true;
  35961. },
  35962. enumerable: true,
  35963. configurable: true
  35964. });
  35965. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35966. /**
  35967. * Gets the midtones Saturation value.
  35968. * 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.
  35969. */
  35970. get: function () {
  35971. return this._midtonesSaturation;
  35972. },
  35973. /**
  35974. * Sets the midtones Saturation value.
  35975. * 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.
  35976. */
  35977. set: function (value) {
  35978. this._midtonesSaturation = value;
  35979. this._dirty = true;
  35980. },
  35981. enumerable: true,
  35982. configurable: true
  35983. });
  35984. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35985. /**
  35986. * Gets the midtones Exposure value.
  35987. * 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.
  35988. */
  35989. get: function () {
  35990. return this._midtonesExposure;
  35991. },
  35992. /**
  35993. * Sets the midtones Exposure value.
  35994. * 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.
  35995. */
  35996. set: function (value) {
  35997. this._midtonesExposure = value;
  35998. this._dirty = true;
  35999. },
  36000. enumerable: true,
  36001. configurable: true
  36002. });
  36003. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  36004. /**
  36005. * Gets the shadows Hue value.
  36006. * 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).
  36007. */
  36008. get: function () {
  36009. return this._shadowsHue;
  36010. },
  36011. /**
  36012. * Sets the shadows Hue value.
  36013. * 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).
  36014. */
  36015. set: function (value) {
  36016. this._shadowsHue = value;
  36017. this._dirty = true;
  36018. },
  36019. enumerable: true,
  36020. configurable: true
  36021. });
  36022. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  36023. /**
  36024. * Gets the shadows Density value.
  36025. * 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.
  36026. * Values less than zero provide a filter of opposite hue.
  36027. */
  36028. get: function () {
  36029. return this._shadowsDensity;
  36030. },
  36031. /**
  36032. * Sets the shadows Density value.
  36033. * 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.
  36034. * Values less than zero provide a filter of opposite hue.
  36035. */
  36036. set: function (value) {
  36037. this._shadowsDensity = value;
  36038. this._dirty = true;
  36039. },
  36040. enumerable: true,
  36041. configurable: true
  36042. });
  36043. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  36044. /**
  36045. * Gets the shadows Saturation value.
  36046. * 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.
  36047. */
  36048. get: function () {
  36049. return this._shadowsSaturation;
  36050. },
  36051. /**
  36052. * Sets the shadows Saturation value.
  36053. * 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.
  36054. */
  36055. set: function (value) {
  36056. this._shadowsSaturation = value;
  36057. this._dirty = true;
  36058. },
  36059. enumerable: true,
  36060. configurable: true
  36061. });
  36062. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  36063. /**
  36064. * Gets the shadows Exposure value.
  36065. * 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.
  36066. */
  36067. get: function () {
  36068. return this._shadowsExposure;
  36069. },
  36070. /**
  36071. * Sets the shadows Exposure value.
  36072. * 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.
  36073. */
  36074. set: function (value) {
  36075. this._shadowsExposure = value;
  36076. this._dirty = true;
  36077. },
  36078. enumerable: true,
  36079. configurable: true
  36080. });
  36081. ColorCurves.prototype.getClassName = function () {
  36082. return "ColorCurves";
  36083. };
  36084. /**
  36085. * Binds the color curves to the shader.
  36086. * @param colorCurves The color curve to bind
  36087. * @param effect The effect to bind to
  36088. */
  36089. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  36090. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  36091. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  36092. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  36093. if (colorCurves._dirty) {
  36094. colorCurves._dirty = false;
  36095. // Fill in global info.
  36096. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  36097. // Compute highlights info.
  36098. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  36099. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  36100. // Compute midtones info.
  36101. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  36102. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  36103. // Compute shadows info.
  36104. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  36105. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  36106. // Compute deltas (neutral is midtones).
  36107. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  36108. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  36109. }
  36110. if (effect) {
  36111. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  36112. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  36113. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  36114. }
  36115. };
  36116. /**
  36117. * Prepare the list of uniforms associated with the ColorCurves effects.
  36118. * @param uniformsList The list of uniforms used in the effect
  36119. */
  36120. ColorCurves.PrepareUniforms = function (uniformsList) {
  36121. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  36122. };
  36123. /**
  36124. * Returns color grading data based on a hue, density, saturation and exposure value.
  36125. * @param filterHue The hue of the color filter.
  36126. * @param filterDensity The density of the color filter.
  36127. * @param saturation The saturation.
  36128. * @param exposure The exposure.
  36129. * @param result The result data container.
  36130. */
  36131. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  36132. if (hue == null) {
  36133. return;
  36134. }
  36135. hue = ColorCurves.clamp(hue, 0, 360);
  36136. density = ColorCurves.clamp(density, -100, 100);
  36137. saturation = ColorCurves.clamp(saturation, -100, 100);
  36138. exposure = ColorCurves.clamp(exposure, -100, 100);
  36139. // Remap the slider/config filter density with non-linear mapping and also scale by half
  36140. // so that the maximum filter density is only 50% control. This provides fine control
  36141. // for small values and reasonable range.
  36142. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  36143. density *= 0.5;
  36144. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  36145. if (density < 0) {
  36146. density *= -1;
  36147. hue = (hue + 180) % 360;
  36148. }
  36149. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  36150. result.scaleToRef(2, result);
  36151. result.a = 1 + 0.01 * saturation;
  36152. };
  36153. /**
  36154. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  36155. * @param value The input slider value in range [-100,100].
  36156. * @returns Adjusted value.
  36157. */
  36158. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  36159. value /= 100;
  36160. var x = Math.abs(value);
  36161. x = Math.pow(x, 2);
  36162. if (value < 0) {
  36163. x *= -1;
  36164. }
  36165. x *= 100;
  36166. return x;
  36167. };
  36168. /**
  36169. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  36170. * @param hue The hue (H) input.
  36171. * @param saturation The saturation (S) input.
  36172. * @param brightness The brightness (B) input.
  36173. * @result An RGBA color represented as Vector4.
  36174. */
  36175. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36176. var h = ColorCurves.clamp(hue, 0, 360);
  36177. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36178. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36179. if (s === 0) {
  36180. result.r = v;
  36181. result.g = v;
  36182. result.b = v;
  36183. }
  36184. else {
  36185. // sector 0 to 5
  36186. h /= 60;
  36187. var i = Math.floor(h);
  36188. // fractional part of h
  36189. var f = h - i;
  36190. var p = v * (1 - s);
  36191. var q = v * (1 - s * f);
  36192. var t = v * (1 - s * (1 - f));
  36193. switch (i) {
  36194. case 0:
  36195. result.r = v;
  36196. result.g = t;
  36197. result.b = p;
  36198. break;
  36199. case 1:
  36200. result.r = q;
  36201. result.g = v;
  36202. result.b = p;
  36203. break;
  36204. case 2:
  36205. result.r = p;
  36206. result.g = v;
  36207. result.b = t;
  36208. break;
  36209. case 3:
  36210. result.r = p;
  36211. result.g = q;
  36212. result.b = v;
  36213. break;
  36214. case 4:
  36215. result.r = t;
  36216. result.g = p;
  36217. result.b = v;
  36218. break;
  36219. default:// case 5:
  36220. result.r = v;
  36221. result.g = p;
  36222. result.b = q;
  36223. break;
  36224. }
  36225. }
  36226. result.a = 1;
  36227. };
  36228. /**
  36229. * Returns a value clamped between min and max
  36230. * @param value The value to clamp
  36231. * @param min The minimum of value
  36232. * @param max The maximum of value
  36233. * @returns The clamped value.
  36234. */
  36235. ColorCurves.clamp = function (value, min, max) {
  36236. return Math.min(Math.max(value, min), max);
  36237. };
  36238. /**
  36239. * Clones the current color curve instance.
  36240. * @return The cloned curves
  36241. */
  36242. ColorCurves.prototype.clone = function () {
  36243. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36244. };
  36245. /**
  36246. * Serializes the current color curve instance to a json representation.
  36247. * @return a JSON representation
  36248. */
  36249. ColorCurves.prototype.serialize = function () {
  36250. return BABYLON.SerializationHelper.Serialize(this);
  36251. };
  36252. /**
  36253. * Parses the color curve from a json representation.
  36254. * @param source the JSON source to parse
  36255. * @return The parsed curves
  36256. */
  36257. ColorCurves.Parse = function (source) {
  36258. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36259. };
  36260. __decorate([
  36261. BABYLON.serialize()
  36262. ], ColorCurves.prototype, "_globalHue", void 0);
  36263. __decorate([
  36264. BABYLON.serialize()
  36265. ], ColorCurves.prototype, "_globalDensity", void 0);
  36266. __decorate([
  36267. BABYLON.serialize()
  36268. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36269. __decorate([
  36270. BABYLON.serialize()
  36271. ], ColorCurves.prototype, "_globalExposure", void 0);
  36272. __decorate([
  36273. BABYLON.serialize()
  36274. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36275. __decorate([
  36276. BABYLON.serialize()
  36277. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36278. __decorate([
  36279. BABYLON.serialize()
  36280. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36281. __decorate([
  36282. BABYLON.serialize()
  36283. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36284. __decorate([
  36285. BABYLON.serialize()
  36286. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36287. __decorate([
  36288. BABYLON.serialize()
  36289. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36290. __decorate([
  36291. BABYLON.serialize()
  36292. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36293. __decorate([
  36294. BABYLON.serialize()
  36295. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36296. return ColorCurves;
  36297. }());
  36298. BABYLON.ColorCurves = ColorCurves;
  36299. })(BABYLON || (BABYLON = {}));
  36300. //# sourceMappingURL=babylon.colorCurves.js.map
  36301. //# sourceMappingURL=babylon.behavior.js.map
  36302. var BABYLON;
  36303. (function (BABYLON) {
  36304. /**
  36305. * "Static Class" containing the most commonly used helper while dealing with material for
  36306. * rendering purpose.
  36307. *
  36308. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36309. *
  36310. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36311. */
  36312. var MaterialHelper = /** @class */ (function () {
  36313. function MaterialHelper() {
  36314. }
  36315. /**
  36316. * Bind the current view position to an effect.
  36317. * @param effect The effect to be bound
  36318. * @param scene The scene the eyes position is used from
  36319. */
  36320. MaterialHelper.BindEyePosition = function (effect, scene) {
  36321. if (scene._forcedViewPosition) {
  36322. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36323. return;
  36324. }
  36325. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36326. };
  36327. /**
  36328. * Helps preparing the defines values about the UVs in used in the effect.
  36329. * UVs are shared as much as we can accross chanels in the shaders.
  36330. * @param texture The texture we are preparing the UVs for
  36331. * @param defines The defines to update
  36332. * @param key The chanel key "diffuse", "specular"... used in the shader
  36333. */
  36334. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36335. defines._needUVs = true;
  36336. defines[key] = true;
  36337. if (texture.getTextureMatrix().isIdentity(true)) {
  36338. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36339. if (texture.coordinatesIndex === 0) {
  36340. defines["MAINUV1"] = true;
  36341. }
  36342. else {
  36343. defines["MAINUV2"] = true;
  36344. }
  36345. }
  36346. else {
  36347. defines[key + "DIRECTUV"] = 0;
  36348. }
  36349. };
  36350. /**
  36351. * Binds a texture matrix value to its corrsponding uniform
  36352. * @param texture The texture to bind the matrix for
  36353. * @param uniformBuffer The uniform buffer receivin the data
  36354. * @param key The chanel key "diffuse", "specular"... used in the shader
  36355. */
  36356. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36357. var matrix = texture.getTextureMatrix();
  36358. if (!matrix.isIdentity(true)) {
  36359. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36360. }
  36361. };
  36362. /**
  36363. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36364. * @param mesh defines the current mesh
  36365. * @param scene defines the current scene
  36366. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36367. * @param pointsCloud defines if point cloud rendering has to be turned on
  36368. * @param fogEnabled defines if fog has to be turned on
  36369. * @param alphaTest defines if alpha testing has to be turned on
  36370. * @param defines defines the current list of defines
  36371. */
  36372. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36373. if (defines._areMiscDirty) {
  36374. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36375. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36376. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36377. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36378. defines["ALPHATEST"] = alphaTest;
  36379. }
  36380. };
  36381. /**
  36382. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36383. * @param scene defines the current scene
  36384. * @param engine defines the current engine
  36385. * @param defines specifies the list of active defines
  36386. * @param useInstances defines if instances have to be turned on
  36387. */
  36388. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36389. var changed = false;
  36390. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36391. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36392. changed = true;
  36393. }
  36394. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36395. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36396. changed = true;
  36397. }
  36398. if (defines["INSTANCES"] !== useInstances) {
  36399. defines["INSTANCES"] = useInstances;
  36400. changed = true;
  36401. }
  36402. if (changed) {
  36403. defines.markAsUnprocessed();
  36404. }
  36405. };
  36406. /**
  36407. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36408. * @param mesh The mesh containing the geometry data we will draw
  36409. * @param defines The defines to update
  36410. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36411. * @param useBones Precise whether bones should be used or not (override mesh info)
  36412. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36413. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36414. * @returns false if defines are considered not dirty and have not been checked
  36415. */
  36416. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36417. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36418. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36419. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36420. return false;
  36421. }
  36422. defines._normals = defines._needNormals;
  36423. defines._uvs = defines._needUVs;
  36424. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36425. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36426. defines["TANGENT"] = true;
  36427. }
  36428. if (defines._needUVs) {
  36429. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36430. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36431. }
  36432. else {
  36433. defines["UV1"] = false;
  36434. defines["UV2"] = false;
  36435. }
  36436. if (useVertexColor) {
  36437. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36438. defines["VERTEXCOLOR"] = hasVertexColors;
  36439. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36440. }
  36441. if (useBones) {
  36442. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36443. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36444. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36445. }
  36446. else {
  36447. defines["NUM_BONE_INFLUENCERS"] = 0;
  36448. defines["BonesPerMesh"] = 0;
  36449. }
  36450. }
  36451. if (useMorphTargets) {
  36452. var manager = mesh.morphTargetManager;
  36453. if (manager) {
  36454. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36455. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36456. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36457. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36458. }
  36459. else {
  36460. defines["MORPHTARGETS_TANGENT"] = false;
  36461. defines["MORPHTARGETS_NORMAL"] = false;
  36462. defines["MORPHTARGETS"] = false;
  36463. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36464. }
  36465. }
  36466. return true;
  36467. };
  36468. /**
  36469. * Prepares the defines related to the light information passed in parameter
  36470. * @param scene The scene we are intending to draw
  36471. * @param mesh The mesh the effect is compiling for
  36472. * @param defines The defines to update
  36473. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36474. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36475. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36476. * @returns true if normals will be required for the rest of the effect
  36477. */
  36478. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36479. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36480. if (disableLighting === void 0) { disableLighting = false; }
  36481. if (!defines._areLightsDirty) {
  36482. return defines._needNormals;
  36483. }
  36484. var lightIndex = 0;
  36485. var needNormals = false;
  36486. var needRebuild = false;
  36487. var lightmapMode = false;
  36488. var shadowEnabled = false;
  36489. var specularEnabled = false;
  36490. if (scene.lightsEnabled && !disableLighting) {
  36491. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36492. var light = _a[_i];
  36493. needNormals = true;
  36494. if (defines["LIGHT" + lightIndex] === undefined) {
  36495. needRebuild = true;
  36496. }
  36497. defines["LIGHT" + lightIndex] = true;
  36498. defines["SPOTLIGHT" + lightIndex] = false;
  36499. defines["HEMILIGHT" + lightIndex] = false;
  36500. defines["POINTLIGHT" + lightIndex] = false;
  36501. defines["DIRLIGHT" + lightIndex] = false;
  36502. var type;
  36503. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36504. type = "SPOTLIGHT" + lightIndex;
  36505. var spotLight = light;
  36506. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  36507. }
  36508. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36509. type = "HEMILIGHT" + lightIndex;
  36510. }
  36511. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36512. type = "POINTLIGHT" + lightIndex;
  36513. }
  36514. else {
  36515. type = "DIRLIGHT" + lightIndex;
  36516. }
  36517. defines[type] = true;
  36518. // Specular
  36519. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36520. specularEnabled = true;
  36521. }
  36522. // Shadows
  36523. defines["SHADOW" + lightIndex] = false;
  36524. defines["SHADOWPCF" + lightIndex] = false;
  36525. defines["SHADOWESM" + lightIndex] = false;
  36526. defines["SHADOWCUBE" + lightIndex] = false;
  36527. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36528. var shadowGenerator = light.getShadowGenerator();
  36529. if (shadowGenerator) {
  36530. shadowEnabled = true;
  36531. shadowGenerator.prepareDefines(defines, lightIndex);
  36532. }
  36533. }
  36534. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36535. lightmapMode = true;
  36536. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36537. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36538. }
  36539. else {
  36540. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36541. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36542. }
  36543. lightIndex++;
  36544. if (lightIndex === maxSimultaneousLights)
  36545. break;
  36546. }
  36547. }
  36548. defines["SPECULARTERM"] = specularEnabled;
  36549. defines["SHADOWS"] = shadowEnabled;
  36550. // Resetting all other lights if any
  36551. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36552. if (defines["LIGHT" + index] !== undefined) {
  36553. defines["LIGHT" + index] = false;
  36554. defines["HEMILIGHT" + lightIndex] = false;
  36555. defines["POINTLIGHT" + lightIndex] = false;
  36556. defines["DIRLIGHT" + lightIndex] = false;
  36557. defines["SPOTLIGHT" + lightIndex] = false;
  36558. defines["SHADOW" + lightIndex] = false;
  36559. }
  36560. }
  36561. var caps = scene.getEngine().getCaps();
  36562. if (defines["SHADOWFLOAT"] === undefined) {
  36563. needRebuild = true;
  36564. }
  36565. defines["SHADOWFLOAT"] = shadowEnabled &&
  36566. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36567. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36568. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36569. if (needRebuild) {
  36570. defines.rebuild();
  36571. }
  36572. return needNormals;
  36573. };
  36574. /**
  36575. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36576. * that won t be acctive due to defines being turned off.
  36577. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36578. * @param samplersList The samplers list
  36579. * @param defines The defines helping in the list generation
  36580. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36581. */
  36582. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36583. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36584. var uniformsList;
  36585. var uniformBuffersList = null;
  36586. if (uniformsListOrOptions.uniformsNames) {
  36587. var options = uniformsListOrOptions;
  36588. uniformsList = options.uniformsNames;
  36589. uniformBuffersList = options.uniformBuffersNames;
  36590. samplersList = options.samplers;
  36591. defines = options.defines;
  36592. maxSimultaneousLights = options.maxSimultaneousLights;
  36593. }
  36594. else {
  36595. uniformsList = uniformsListOrOptions;
  36596. if (!samplersList) {
  36597. samplersList = [];
  36598. }
  36599. }
  36600. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36601. if (!defines["LIGHT" + lightIndex]) {
  36602. break;
  36603. }
  36604. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36605. if (uniformBuffersList) {
  36606. uniformBuffersList.push("Light" + lightIndex);
  36607. }
  36608. samplersList.push("shadowSampler" + lightIndex);
  36609. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36610. samplersList.push("projectionLightSampler" + lightIndex);
  36611. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36612. }
  36613. }
  36614. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36615. uniformsList.push("morphTargetInfluences");
  36616. }
  36617. };
  36618. /**
  36619. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36620. * @param defines The defines to update while falling back
  36621. * @param fallbacks The authorized effect fallbacks
  36622. * @param maxSimultaneousLights The maximum number of lights allowed
  36623. * @param rank the current rank of the Effect
  36624. * @returns The newly affected rank
  36625. */
  36626. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36627. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36628. if (rank === void 0) { rank = 0; }
  36629. var lightFallbackRank = 0;
  36630. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36631. if (!defines["LIGHT" + lightIndex]) {
  36632. break;
  36633. }
  36634. if (lightIndex > 0) {
  36635. lightFallbackRank = rank + lightIndex;
  36636. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36637. }
  36638. if (!defines["SHADOWS"]) {
  36639. if (defines["SHADOW" + lightIndex]) {
  36640. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36641. }
  36642. if (defines["SHADOWPCF" + lightIndex]) {
  36643. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36644. }
  36645. if (defines["SHADOWESM" + lightIndex]) {
  36646. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36647. }
  36648. }
  36649. }
  36650. return lightFallbackRank++;
  36651. };
  36652. /**
  36653. * Prepares the list of attributes required for morph targets according to the effect defines.
  36654. * @param attribs The current list of supported attribs
  36655. * @param mesh The mesh to prepare the morph targets attributes for
  36656. * @param defines The current Defines of the effect
  36657. */
  36658. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36659. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36660. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36661. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36662. var manager = mesh.morphTargetManager;
  36663. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36664. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36665. for (var index = 0; index < influencers; index++) {
  36666. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36667. if (normal) {
  36668. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36669. }
  36670. if (tangent) {
  36671. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36672. }
  36673. if (attribs.length > maxAttributesCount) {
  36674. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36675. }
  36676. }
  36677. }
  36678. };
  36679. /**
  36680. * Prepares the list of attributes required for bones according to the effect defines.
  36681. * @param attribs The current list of supported attribs
  36682. * @param mesh The mesh to prepare the bones attributes for
  36683. * @param defines The current Defines of the effect
  36684. * @param fallbacks The current efffect fallback strategy
  36685. */
  36686. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36687. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36688. fallbacks.addCPUSkinningFallback(0, mesh);
  36689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36691. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36694. }
  36695. }
  36696. };
  36697. /**
  36698. * Prepares the list of attributes required for instances according to the effect defines.
  36699. * @param attribs The current list of supported attribs
  36700. * @param defines The current Defines of the effect
  36701. */
  36702. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36703. if (defines["INSTANCES"]) {
  36704. attribs.push("world0");
  36705. attribs.push("world1");
  36706. attribs.push("world2");
  36707. attribs.push("world3");
  36708. }
  36709. };
  36710. /**
  36711. * Binds the light shadow information to the effect for the given mesh.
  36712. * @param light The light containing the generator
  36713. * @param scene The scene the lights belongs to
  36714. * @param mesh The mesh we are binding the information to render
  36715. * @param lightIndex The light index in the effect used to render the mesh
  36716. * @param effect The effect we are binding the data to
  36717. */
  36718. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36719. if (light.shadowEnabled && mesh.receiveShadows) {
  36720. var shadowGenerator = light.getShadowGenerator();
  36721. if (shadowGenerator) {
  36722. shadowGenerator.bindShadowLight(lightIndex, effect);
  36723. }
  36724. }
  36725. };
  36726. /**
  36727. * Binds the light information to the effect.
  36728. * @param light The light containing the generator
  36729. * @param effect The effect we are binding the data to
  36730. * @param lightIndex The light index in the effect used to render
  36731. */
  36732. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36733. light.transferToEffect(effect, lightIndex + "");
  36734. };
  36735. /**
  36736. * Binds the lights information from the scene to the effect for the given mesh.
  36737. * @param scene The scene the lights belongs to
  36738. * @param mesh The mesh we are binding the information to render
  36739. * @param effect The effect we are binding the data to
  36740. * @param defines The generated defines for the effect
  36741. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36742. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36743. */
  36744. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36745. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36746. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36747. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36748. for (var i = 0; i < len; i++) {
  36749. var light = mesh._lightSources[i];
  36750. var iAsString = i.toString();
  36751. var scaledIntensity = light.getScaledIntensity();
  36752. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36753. MaterialHelper.BindLightProperties(light, effect, i);
  36754. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36755. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36756. if (defines["SPECULARTERM"]) {
  36757. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36758. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36759. }
  36760. // Shadows
  36761. if (scene.shadowsEnabled) {
  36762. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36763. }
  36764. light._uniformBuffer.update();
  36765. }
  36766. };
  36767. /**
  36768. * Binds the fog information from the scene to the effect for the given mesh.
  36769. * @param scene The scene the lights belongs to
  36770. * @param mesh The mesh we are binding the information to render
  36771. * @param effect The effect we are binding the data to
  36772. */
  36773. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36774. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36775. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36776. effect.setColor3("vFogColor", scene.fogColor);
  36777. }
  36778. };
  36779. /**
  36780. * Binds the bones information from the mesh to the effect.
  36781. * @param mesh The mesh we are binding the information to render
  36782. * @param effect The effect we are binding the data to
  36783. */
  36784. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36785. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36786. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36787. if (matrices && effect) {
  36788. effect.setMatrices("mBones", matrices);
  36789. }
  36790. }
  36791. };
  36792. /**
  36793. * Binds the morph targets information from the mesh to the effect.
  36794. * @param abstractMesh The mesh we are binding the information to render
  36795. * @param effect The effect we are binding the data to
  36796. */
  36797. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36798. var manager = abstractMesh.morphTargetManager;
  36799. if (!abstractMesh || !manager) {
  36800. return;
  36801. }
  36802. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36803. };
  36804. /**
  36805. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36806. * @param defines The generated defines used in the effect
  36807. * @param effect The effect we are binding the data to
  36808. * @param scene The scene we are willing to render with logarithmic scale for
  36809. */
  36810. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36811. if (defines["LOGARITHMICDEPTH"]) {
  36812. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36813. }
  36814. };
  36815. /**
  36816. * Binds the clip plane information from the scene to the effect.
  36817. * @param scene The scene the clip plane information are extracted from
  36818. * @param effect The effect we are binding the data to
  36819. */
  36820. MaterialHelper.BindClipPlane = function (effect, scene) {
  36821. if (scene.clipPlane) {
  36822. var clipPlane = scene.clipPlane;
  36823. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36824. }
  36825. };
  36826. return MaterialHelper;
  36827. }());
  36828. BABYLON.MaterialHelper = MaterialHelper;
  36829. })(BABYLON || (BABYLON = {}));
  36830. //# sourceMappingURL=babylon.materialHelper.js.map
  36831. var BABYLON;
  36832. (function (BABYLON) {
  36833. var PushMaterial = /** @class */ (function (_super) {
  36834. __extends(PushMaterial, _super);
  36835. function PushMaterial(name, scene) {
  36836. var _this = _super.call(this, name, scene) || this;
  36837. _this.storeEffectOnSubMeshes = true;
  36838. return _this;
  36839. }
  36840. PushMaterial.prototype.getEffect = function () {
  36841. return this._activeEffect;
  36842. };
  36843. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36844. if (!mesh) {
  36845. return false;
  36846. }
  36847. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36848. return true;
  36849. }
  36850. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36851. };
  36852. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36853. this._activeEffect.setMatrix("world", world);
  36854. };
  36855. PushMaterial.prototype.bind = function (world, mesh) {
  36856. if (!mesh) {
  36857. return;
  36858. }
  36859. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36860. };
  36861. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36862. if (effect === void 0) { effect = null; }
  36863. _super.prototype._afterBind.call(this, mesh);
  36864. this.getScene()._cachedEffect = effect;
  36865. };
  36866. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36867. if (visibility === void 0) { visibility = 1; }
  36868. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36869. };
  36870. return PushMaterial;
  36871. }(BABYLON.Material));
  36872. BABYLON.PushMaterial = PushMaterial;
  36873. })(BABYLON || (BABYLON = {}));
  36874. //# sourceMappingURL=babylon.pushMaterial.js.map
  36875. var BABYLON;
  36876. (function (BABYLON) {
  36877. var StandardMaterialDefines = /** @class */ (function (_super) {
  36878. __extends(StandardMaterialDefines, _super);
  36879. function StandardMaterialDefines() {
  36880. var _this = _super.call(this) || this;
  36881. _this.MAINUV1 = false;
  36882. _this.MAINUV2 = false;
  36883. _this.DIFFUSE = false;
  36884. _this.DIFFUSEDIRECTUV = 0;
  36885. _this.AMBIENT = false;
  36886. _this.AMBIENTDIRECTUV = 0;
  36887. _this.OPACITY = false;
  36888. _this.OPACITYDIRECTUV = 0;
  36889. _this.OPACITYRGB = false;
  36890. _this.REFLECTION = false;
  36891. _this.EMISSIVE = false;
  36892. _this.EMISSIVEDIRECTUV = 0;
  36893. _this.SPECULAR = false;
  36894. _this.SPECULARDIRECTUV = 0;
  36895. _this.BUMP = false;
  36896. _this.BUMPDIRECTUV = 0;
  36897. _this.PARALLAX = false;
  36898. _this.PARALLAXOCCLUSION = false;
  36899. _this.SPECULAROVERALPHA = false;
  36900. _this.CLIPPLANE = false;
  36901. _this.ALPHATEST = false;
  36902. _this.DEPTHPREPASS = false;
  36903. _this.ALPHAFROMDIFFUSE = false;
  36904. _this.POINTSIZE = false;
  36905. _this.FOG = false;
  36906. _this.SPECULARTERM = false;
  36907. _this.DIFFUSEFRESNEL = false;
  36908. _this.OPACITYFRESNEL = false;
  36909. _this.REFLECTIONFRESNEL = false;
  36910. _this.REFRACTIONFRESNEL = false;
  36911. _this.EMISSIVEFRESNEL = false;
  36912. _this.FRESNEL = false;
  36913. _this.NORMAL = false;
  36914. _this.UV1 = false;
  36915. _this.UV2 = false;
  36916. _this.VERTEXCOLOR = false;
  36917. _this.VERTEXALPHA = false;
  36918. _this.NUM_BONE_INFLUENCERS = 0;
  36919. _this.BonesPerMesh = 0;
  36920. _this.INSTANCES = false;
  36921. _this.GLOSSINESS = false;
  36922. _this.ROUGHNESS = false;
  36923. _this.EMISSIVEASILLUMINATION = false;
  36924. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36925. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36926. _this.LIGHTMAP = false;
  36927. _this.LIGHTMAPDIRECTUV = 0;
  36928. _this.USELIGHTMAPASSHADOWMAP = false;
  36929. _this.REFLECTIONMAP_3D = false;
  36930. _this.REFLECTIONMAP_SPHERICAL = false;
  36931. _this.REFLECTIONMAP_PLANAR = false;
  36932. _this.REFLECTIONMAP_CUBIC = false;
  36933. _this.REFLECTIONMAP_PROJECTION = false;
  36934. _this.REFLECTIONMAP_SKYBOX = false;
  36935. _this.REFLECTIONMAP_EXPLICIT = false;
  36936. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36937. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36938. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36939. _this.INVERTCUBICMAP = false;
  36940. _this.LOGARITHMICDEPTH = false;
  36941. _this.REFRACTION = false;
  36942. _this.REFRACTIONMAP_3D = false;
  36943. _this.REFLECTIONOVERALPHA = false;
  36944. _this.TWOSIDEDLIGHTING = false;
  36945. _this.SHADOWFLOAT = false;
  36946. _this.MORPHTARGETS = false;
  36947. _this.MORPHTARGETS_NORMAL = false;
  36948. _this.MORPHTARGETS_TANGENT = false;
  36949. _this.NUM_MORPH_INFLUENCERS = 0;
  36950. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36951. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36952. _this.IMAGEPROCESSING = false;
  36953. _this.VIGNETTE = false;
  36954. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36955. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36956. _this.TONEMAPPING = false;
  36957. _this.CONTRAST = false;
  36958. _this.COLORCURVES = false;
  36959. _this.COLORGRADING = false;
  36960. _this.COLORGRADING3D = false;
  36961. _this.SAMPLER3DGREENDEPTH = false;
  36962. _this.SAMPLER3DBGRMAP = false;
  36963. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36964. _this.EXPOSURE = false;
  36965. _this.rebuild();
  36966. return _this;
  36967. }
  36968. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36969. var modes = [
  36970. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36971. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36972. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36973. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36974. ];
  36975. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36976. var mode = modes_1[_i];
  36977. this[mode] = (mode === modeToEnable);
  36978. }
  36979. };
  36980. return StandardMaterialDefines;
  36981. }(BABYLON.MaterialDefines));
  36982. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36983. var StandardMaterial = /** @class */ (function (_super) {
  36984. __extends(StandardMaterial, _super);
  36985. function StandardMaterial(name, scene) {
  36986. var _this = _super.call(this, name, scene) || this;
  36987. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36988. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36989. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36990. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36991. _this.specularPower = 64;
  36992. _this._useAlphaFromDiffuseTexture = false;
  36993. _this._useEmissiveAsIllumination = false;
  36994. _this._linkEmissiveWithDiffuse = false;
  36995. _this._useSpecularOverAlpha = false;
  36996. _this._useReflectionOverAlpha = false;
  36997. _this._disableLighting = false;
  36998. _this._useParallax = false;
  36999. _this._useParallaxOcclusion = false;
  37000. _this.parallaxScaleBias = 0.05;
  37001. _this._roughness = 0;
  37002. _this.indexOfRefraction = 0.98;
  37003. _this.invertRefractionY = true;
  37004. _this._useLightmapAsShadowmap = false;
  37005. _this._useReflectionFresnelFromSpecular = false;
  37006. _this._useGlossinessFromSpecularMapAlpha = false;
  37007. _this._maxSimultaneousLights = 4;
  37008. /**
  37009. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37010. */
  37011. _this._invertNormalMapX = false;
  37012. /**
  37013. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37014. */
  37015. _this._invertNormalMapY = false;
  37016. /**
  37017. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37018. */
  37019. _this._twoSidedLighting = false;
  37020. _this._renderTargets = new BABYLON.SmartArray(16);
  37021. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37022. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37023. // Setup the default processing configuration to the scene.
  37024. _this._attachImageProcessingConfiguration(null);
  37025. _this.getRenderTargetTextures = function () {
  37026. _this._renderTargets.reset();
  37027. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37028. _this._renderTargets.push(_this._reflectionTexture);
  37029. }
  37030. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37031. _this._renderTargets.push(_this._refractionTexture);
  37032. }
  37033. return _this._renderTargets;
  37034. };
  37035. return _this;
  37036. }
  37037. ;
  37038. ;
  37039. ;
  37040. ;
  37041. ;
  37042. ;
  37043. ;
  37044. ;
  37045. ;
  37046. ;
  37047. ;
  37048. ;
  37049. ;
  37050. ;
  37051. ;
  37052. ;
  37053. ;
  37054. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  37055. /**
  37056. * Gets the image processing configuration used either in this material.
  37057. */
  37058. get: function () {
  37059. return this._imageProcessingConfiguration;
  37060. },
  37061. /**
  37062. * Sets the Default image processing configuration used either in the this material.
  37063. *
  37064. * If sets to null, the scene one is in use.
  37065. */
  37066. set: function (value) {
  37067. this._attachImageProcessingConfiguration(value);
  37068. // Ensure the effect will be rebuilt.
  37069. this._markAllSubMeshesAsTexturesDirty();
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. /**
  37075. * Attaches a new image processing configuration to the Standard Material.
  37076. * @param configuration
  37077. */
  37078. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37079. var _this = this;
  37080. if (configuration === this._imageProcessingConfiguration) {
  37081. return;
  37082. }
  37083. // Detaches observer.
  37084. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37085. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37086. }
  37087. // Pick the scene configuration if needed.
  37088. if (!configuration) {
  37089. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37090. }
  37091. else {
  37092. this._imageProcessingConfiguration = configuration;
  37093. }
  37094. // Attaches observer.
  37095. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37096. _this._markAllSubMeshesAsImageProcessingDirty();
  37097. });
  37098. };
  37099. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  37100. /**
  37101. * Gets wether the color curves effect is enabled.
  37102. */
  37103. get: function () {
  37104. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37105. },
  37106. /**
  37107. * Sets wether the color curves effect is enabled.
  37108. */
  37109. set: function (value) {
  37110. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37111. },
  37112. enumerable: true,
  37113. configurable: true
  37114. });
  37115. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  37116. /**
  37117. * Gets wether the color grading effect is enabled.
  37118. */
  37119. get: function () {
  37120. return this.imageProcessingConfiguration.colorGradingEnabled;
  37121. },
  37122. /**
  37123. * Gets wether the color grading effect is enabled.
  37124. */
  37125. set: function (value) {
  37126. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37127. },
  37128. enumerable: true,
  37129. configurable: true
  37130. });
  37131. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  37132. /**
  37133. * Gets wether tonemapping is enabled or not.
  37134. */
  37135. get: function () {
  37136. return this._imageProcessingConfiguration.toneMappingEnabled;
  37137. },
  37138. /**
  37139. * Sets wether tonemapping is enabled or not
  37140. */
  37141. set: function (value) {
  37142. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37143. },
  37144. enumerable: true,
  37145. configurable: true
  37146. });
  37147. ;
  37148. ;
  37149. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  37150. /**
  37151. * The camera exposure used on this material.
  37152. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37153. * This corresponds to a photographic exposure.
  37154. */
  37155. get: function () {
  37156. return this._imageProcessingConfiguration.exposure;
  37157. },
  37158. /**
  37159. * The camera exposure used on this material.
  37160. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37161. * This corresponds to a photographic exposure.
  37162. */
  37163. set: function (value) {
  37164. this._imageProcessingConfiguration.exposure = value;
  37165. },
  37166. enumerable: true,
  37167. configurable: true
  37168. });
  37169. ;
  37170. ;
  37171. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  37172. /**
  37173. * Gets The camera contrast used on this material.
  37174. */
  37175. get: function () {
  37176. return this._imageProcessingConfiguration.contrast;
  37177. },
  37178. /**
  37179. * Sets The camera contrast used on this material.
  37180. */
  37181. set: function (value) {
  37182. this._imageProcessingConfiguration.contrast = value;
  37183. },
  37184. enumerable: true,
  37185. configurable: true
  37186. });
  37187. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37188. /**
  37189. * Gets the Color Grading 2D Lookup Texture.
  37190. */
  37191. get: function () {
  37192. return this._imageProcessingConfiguration.colorGradingTexture;
  37193. },
  37194. /**
  37195. * Sets the Color Grading 2D Lookup Texture.
  37196. */
  37197. set: function (value) {
  37198. this._imageProcessingConfiguration.colorGradingTexture = value;
  37199. },
  37200. enumerable: true,
  37201. configurable: true
  37202. });
  37203. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37204. /**
  37205. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37206. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37207. * 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;
  37208. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37209. */
  37210. get: function () {
  37211. return this._imageProcessingConfiguration.colorCurves;
  37212. },
  37213. /**
  37214. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37215. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37216. * 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;
  37217. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37218. */
  37219. set: function (value) {
  37220. this._imageProcessingConfiguration.colorCurves = value;
  37221. },
  37222. enumerable: true,
  37223. configurable: true
  37224. });
  37225. StandardMaterial.prototype.getClassName = function () {
  37226. return "StandardMaterial";
  37227. };
  37228. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37229. get: function () {
  37230. return this._useLogarithmicDepth;
  37231. },
  37232. set: function (value) {
  37233. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37234. this._markAllSubMeshesAsMiscDirty();
  37235. },
  37236. enumerable: true,
  37237. configurable: true
  37238. });
  37239. StandardMaterial.prototype.needAlphaBlending = function () {
  37240. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37241. };
  37242. StandardMaterial.prototype.needAlphaTesting = function () {
  37243. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37244. };
  37245. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37246. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37247. };
  37248. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37249. return this._diffuseTexture;
  37250. };
  37251. /**
  37252. * Child classes can use it to update shaders
  37253. */
  37254. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37255. if (useInstances === void 0) { useInstances = false; }
  37256. if (subMesh.effect && this.isFrozen) {
  37257. if (this._wasPreviouslyReady && subMesh.effect) {
  37258. return true;
  37259. }
  37260. }
  37261. if (!subMesh._materialDefines) {
  37262. subMesh._materialDefines = new StandardMaterialDefines();
  37263. }
  37264. var scene = this.getScene();
  37265. var defines = subMesh._materialDefines;
  37266. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37267. if (defines._renderId === scene.getRenderId()) {
  37268. return true;
  37269. }
  37270. }
  37271. var engine = scene.getEngine();
  37272. // Lights
  37273. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37274. // Textures
  37275. if (defines._areTexturesDirty) {
  37276. defines._needUVs = false;
  37277. defines.MAINUV1 = false;
  37278. defines.MAINUV2 = false;
  37279. if (scene.texturesEnabled) {
  37280. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37281. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37282. return false;
  37283. }
  37284. else {
  37285. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37286. }
  37287. }
  37288. else {
  37289. defines.DIFFUSE = false;
  37290. }
  37291. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37292. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37293. return false;
  37294. }
  37295. else {
  37296. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37297. }
  37298. }
  37299. else {
  37300. defines.AMBIENT = false;
  37301. }
  37302. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37303. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37304. return false;
  37305. }
  37306. else {
  37307. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37308. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37309. }
  37310. }
  37311. else {
  37312. defines.OPACITY = false;
  37313. }
  37314. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37315. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37316. return false;
  37317. }
  37318. else {
  37319. defines._needNormals = true;
  37320. defines.REFLECTION = true;
  37321. defines.ROUGHNESS = (this._roughness > 0);
  37322. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37323. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37324. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37325. switch (this._reflectionTexture.coordinatesMode) {
  37326. case BABYLON.Texture.CUBIC_MODE:
  37327. case BABYLON.Texture.INVCUBIC_MODE:
  37328. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37329. break;
  37330. case BABYLON.Texture.EXPLICIT_MODE:
  37331. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37332. break;
  37333. case BABYLON.Texture.PLANAR_MODE:
  37334. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37335. break;
  37336. case BABYLON.Texture.PROJECTION_MODE:
  37337. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37338. break;
  37339. case BABYLON.Texture.SKYBOX_MODE:
  37340. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37341. break;
  37342. case BABYLON.Texture.SPHERICAL_MODE:
  37343. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37344. break;
  37345. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37346. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37347. break;
  37348. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37349. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37350. break;
  37351. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37352. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37353. break;
  37354. }
  37355. }
  37356. }
  37357. else {
  37358. defines.REFLECTION = false;
  37359. }
  37360. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37361. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37362. return false;
  37363. }
  37364. else {
  37365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37366. }
  37367. }
  37368. else {
  37369. defines.EMISSIVE = false;
  37370. }
  37371. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37372. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37373. return false;
  37374. }
  37375. else {
  37376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37377. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37378. }
  37379. }
  37380. else {
  37381. defines.LIGHTMAP = false;
  37382. }
  37383. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37384. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37385. return false;
  37386. }
  37387. else {
  37388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37389. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37390. }
  37391. }
  37392. else {
  37393. defines.SPECULAR = false;
  37394. }
  37395. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37396. // Bump texure can not be not blocking.
  37397. if (!this._bumpTexture.isReady()) {
  37398. return false;
  37399. }
  37400. else {
  37401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37402. defines.PARALLAX = this._useParallax;
  37403. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37404. }
  37405. }
  37406. else {
  37407. defines.BUMP = false;
  37408. }
  37409. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37410. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37411. return false;
  37412. }
  37413. else {
  37414. defines._needUVs = true;
  37415. defines.REFRACTION = true;
  37416. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37417. }
  37418. }
  37419. else {
  37420. defines.REFRACTION = false;
  37421. }
  37422. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37423. }
  37424. else {
  37425. defines.DIFFUSE = false;
  37426. defines.AMBIENT = false;
  37427. defines.OPACITY = false;
  37428. defines.REFLECTION = false;
  37429. defines.EMISSIVE = false;
  37430. defines.LIGHTMAP = false;
  37431. defines.BUMP = false;
  37432. defines.REFRACTION = false;
  37433. }
  37434. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37435. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37436. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37437. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37438. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37439. }
  37440. if (defines._areImageProcessingDirty) {
  37441. if (!this._imageProcessingConfiguration.isReady()) {
  37442. return false;
  37443. }
  37444. this._imageProcessingConfiguration.prepareDefines(defines);
  37445. }
  37446. if (defines._areFresnelDirty) {
  37447. if (StandardMaterial.FresnelEnabled) {
  37448. // Fresnel
  37449. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37450. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37451. this._reflectionFresnelParameters) {
  37452. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37453. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37454. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37455. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37456. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37457. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37458. defines._needNormals = true;
  37459. defines.FRESNEL = true;
  37460. }
  37461. }
  37462. else {
  37463. defines.FRESNEL = false;
  37464. }
  37465. }
  37466. // Misc.
  37467. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37468. // Attribs
  37469. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37470. // Values that need to be evaluated on every frame
  37471. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37472. // Get correct effect
  37473. if (defines.isDirty) {
  37474. defines.markAsProcessed();
  37475. scene.resetCachedMaterial();
  37476. // Fallbacks
  37477. var fallbacks = new BABYLON.EffectFallbacks();
  37478. if (defines.REFLECTION) {
  37479. fallbacks.addFallback(0, "REFLECTION");
  37480. }
  37481. if (defines.SPECULAR) {
  37482. fallbacks.addFallback(0, "SPECULAR");
  37483. }
  37484. if (defines.BUMP) {
  37485. fallbacks.addFallback(0, "BUMP");
  37486. }
  37487. if (defines.PARALLAX) {
  37488. fallbacks.addFallback(1, "PARALLAX");
  37489. }
  37490. if (defines.PARALLAXOCCLUSION) {
  37491. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37492. }
  37493. if (defines.SPECULAROVERALPHA) {
  37494. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37495. }
  37496. if (defines.FOG) {
  37497. fallbacks.addFallback(1, "FOG");
  37498. }
  37499. if (defines.POINTSIZE) {
  37500. fallbacks.addFallback(0, "POINTSIZE");
  37501. }
  37502. if (defines.LOGARITHMICDEPTH) {
  37503. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37504. }
  37505. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37506. if (defines.SPECULARTERM) {
  37507. fallbacks.addFallback(0, "SPECULARTERM");
  37508. }
  37509. if (defines.DIFFUSEFRESNEL) {
  37510. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37511. }
  37512. if (defines.OPACITYFRESNEL) {
  37513. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37514. }
  37515. if (defines.REFLECTIONFRESNEL) {
  37516. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37517. }
  37518. if (defines.EMISSIVEFRESNEL) {
  37519. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37520. }
  37521. if (defines.FRESNEL) {
  37522. fallbacks.addFallback(4, "FRESNEL");
  37523. }
  37524. //Attributes
  37525. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37526. if (defines.NORMAL) {
  37527. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37528. }
  37529. if (defines.UV1) {
  37530. attribs.push(BABYLON.VertexBuffer.UVKind);
  37531. }
  37532. if (defines.UV2) {
  37533. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37534. }
  37535. if (defines.VERTEXCOLOR) {
  37536. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37537. }
  37538. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37539. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37540. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37541. var shaderName = "default";
  37542. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37543. "vFogInfos", "vFogColor", "pointSize",
  37544. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37545. "mBones",
  37546. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37547. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37548. "logarithmicDepthConstant", "vTangentSpaceParams"
  37549. ];
  37550. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37551. var uniformBuffers = ["Material", "Scene"];
  37552. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37553. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37554. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37555. uniformsNames: uniforms,
  37556. uniformBuffersNames: uniformBuffers,
  37557. samplers: samplers,
  37558. defines: defines,
  37559. maxSimultaneousLights: this._maxSimultaneousLights
  37560. });
  37561. if (this.customShaderNameResolve) {
  37562. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37563. }
  37564. var join = defines.toString();
  37565. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37566. attributes: attribs,
  37567. uniformsNames: uniforms,
  37568. uniformBuffersNames: uniformBuffers,
  37569. samplers: samplers,
  37570. defines: join,
  37571. fallbacks: fallbacks,
  37572. onCompiled: this.onCompiled,
  37573. onError: this.onError,
  37574. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37575. }, engine), defines);
  37576. this.buildUniformLayout();
  37577. }
  37578. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37579. return false;
  37580. }
  37581. defines._renderId = scene.getRenderId();
  37582. this._wasPreviouslyReady = true;
  37583. return true;
  37584. };
  37585. StandardMaterial.prototype.buildUniformLayout = function () {
  37586. // Order is important !
  37587. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37588. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37589. this._uniformBuffer.addUniform("opacityParts", 4);
  37590. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37591. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37592. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37593. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37594. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37595. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37596. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37597. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37598. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37599. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37600. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37601. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37602. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37603. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37604. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37605. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37606. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37607. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37608. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37609. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37610. this._uniformBuffer.addUniform("specularMatrix", 16);
  37611. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37612. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37613. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37614. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37615. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37616. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37617. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37618. this._uniformBuffer.addUniform("pointSize", 1);
  37619. this._uniformBuffer.create();
  37620. };
  37621. StandardMaterial.prototype.unbind = function () {
  37622. if (this._activeEffect) {
  37623. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37624. this._activeEffect.setTexture("reflection2DSampler", null);
  37625. }
  37626. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37627. this._activeEffect.setTexture("refraction2DSampler", null);
  37628. }
  37629. }
  37630. _super.prototype.unbind.call(this);
  37631. };
  37632. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37633. var scene = this.getScene();
  37634. var defines = subMesh._materialDefines;
  37635. if (!defines) {
  37636. return;
  37637. }
  37638. var effect = subMesh.effect;
  37639. if (!effect) {
  37640. return;
  37641. }
  37642. this._activeEffect = effect;
  37643. // Matrices
  37644. this.bindOnlyWorldMatrix(world);
  37645. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37646. // Bones
  37647. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37648. if (mustRebind) {
  37649. this._uniformBuffer.bindToEffect(effect, "Material");
  37650. this.bindViewProjection(effect);
  37651. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37652. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37653. // Fresnel
  37654. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37655. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37656. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37657. }
  37658. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37659. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37660. }
  37661. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37662. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37663. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37664. }
  37665. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37666. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37667. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37668. }
  37669. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37670. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37671. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37672. }
  37673. }
  37674. // Textures
  37675. if (scene.texturesEnabled) {
  37676. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37677. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37678. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37679. }
  37680. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37681. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37682. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37683. }
  37684. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37685. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37686. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37687. }
  37688. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37689. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37690. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37691. }
  37692. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37693. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37694. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37695. }
  37696. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37697. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37698. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37699. }
  37700. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37701. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37702. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37703. }
  37704. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37705. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37706. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37707. if (scene._mirroredCameraPosition) {
  37708. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37709. }
  37710. else {
  37711. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37712. }
  37713. }
  37714. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37715. var depth = 1.0;
  37716. if (!this._refractionTexture.isCube) {
  37717. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37718. if (this._refractionTexture.depth) {
  37719. depth = this._refractionTexture.depth;
  37720. }
  37721. }
  37722. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37723. }
  37724. }
  37725. // Point size
  37726. if (this.pointsCloud) {
  37727. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37728. }
  37729. if (defines.SPECULARTERM) {
  37730. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37731. }
  37732. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37733. // Diffuse
  37734. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37735. }
  37736. // Textures
  37737. if (scene.texturesEnabled) {
  37738. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37739. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37740. }
  37741. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37742. effect.setTexture("ambientSampler", this._ambientTexture);
  37743. }
  37744. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37745. effect.setTexture("opacitySampler", this._opacityTexture);
  37746. }
  37747. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37748. if (this._reflectionTexture.isCube) {
  37749. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37750. }
  37751. else {
  37752. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37753. }
  37754. }
  37755. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37756. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37757. }
  37758. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37759. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37760. }
  37761. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37762. effect.setTexture("specularSampler", this._specularTexture);
  37763. }
  37764. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37765. effect.setTexture("bumpSampler", this._bumpTexture);
  37766. }
  37767. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37768. var depth = 1.0;
  37769. if (this._refractionTexture.isCube) {
  37770. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37771. }
  37772. else {
  37773. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37774. }
  37775. }
  37776. }
  37777. // Clip plane
  37778. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37779. // Colors
  37780. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37781. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37782. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37783. }
  37784. if (mustRebind || !this.isFrozen) {
  37785. // Lights
  37786. if (scene.lightsEnabled && !this._disableLighting) {
  37787. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37788. }
  37789. // View
  37790. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37791. this.bindView(effect);
  37792. }
  37793. // Fog
  37794. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37795. // Morph targets
  37796. if (defines.NUM_MORPH_INFLUENCERS) {
  37797. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37798. }
  37799. // Log. depth
  37800. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37801. // image processing
  37802. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37803. this._imageProcessingConfiguration.bind(this._activeEffect);
  37804. }
  37805. }
  37806. this._uniformBuffer.update();
  37807. this._afterBind(mesh, this._activeEffect);
  37808. };
  37809. StandardMaterial.prototype.getAnimatables = function () {
  37810. var results = [];
  37811. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37812. results.push(this._diffuseTexture);
  37813. }
  37814. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37815. results.push(this._ambientTexture);
  37816. }
  37817. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37818. results.push(this._opacityTexture);
  37819. }
  37820. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37821. results.push(this._reflectionTexture);
  37822. }
  37823. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37824. results.push(this._emissiveTexture);
  37825. }
  37826. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37827. results.push(this._specularTexture);
  37828. }
  37829. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37830. results.push(this._bumpTexture);
  37831. }
  37832. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37833. results.push(this._lightmapTexture);
  37834. }
  37835. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37836. results.push(this._refractionTexture);
  37837. }
  37838. return results;
  37839. };
  37840. StandardMaterial.prototype.getActiveTextures = function () {
  37841. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37842. if (this._diffuseTexture) {
  37843. activeTextures.push(this._diffuseTexture);
  37844. }
  37845. if (this._ambientTexture) {
  37846. activeTextures.push(this._ambientTexture);
  37847. }
  37848. if (this._opacityTexture) {
  37849. activeTextures.push(this._opacityTexture);
  37850. }
  37851. if (this._reflectionTexture) {
  37852. activeTextures.push(this._reflectionTexture);
  37853. }
  37854. if (this._emissiveTexture) {
  37855. activeTextures.push(this._emissiveTexture);
  37856. }
  37857. if (this._specularTexture) {
  37858. activeTextures.push(this._specularTexture);
  37859. }
  37860. if (this._bumpTexture) {
  37861. activeTextures.push(this._bumpTexture);
  37862. }
  37863. if (this._lightmapTexture) {
  37864. activeTextures.push(this._lightmapTexture);
  37865. }
  37866. if (this._refractionTexture) {
  37867. activeTextures.push(this._refractionTexture);
  37868. }
  37869. return activeTextures;
  37870. };
  37871. StandardMaterial.prototype.hasTexture = function (texture) {
  37872. if (_super.prototype.hasTexture.call(this, texture)) {
  37873. return true;
  37874. }
  37875. if (this._diffuseTexture === texture) {
  37876. return true;
  37877. }
  37878. if (this._ambientTexture === texture) {
  37879. return true;
  37880. }
  37881. if (this._opacityTexture === texture) {
  37882. return true;
  37883. }
  37884. if (this._reflectionTexture === texture) {
  37885. return true;
  37886. }
  37887. if (this._emissiveTexture === texture) {
  37888. return true;
  37889. }
  37890. if (this._specularTexture === texture) {
  37891. return true;
  37892. }
  37893. if (this._bumpTexture === texture) {
  37894. return true;
  37895. }
  37896. if (this._lightmapTexture === texture) {
  37897. return true;
  37898. }
  37899. if (this._refractionTexture === texture) {
  37900. return true;
  37901. }
  37902. return false;
  37903. };
  37904. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37905. if (forceDisposeTextures) {
  37906. if (this._diffuseTexture) {
  37907. this._diffuseTexture.dispose();
  37908. }
  37909. if (this._ambientTexture) {
  37910. this._ambientTexture.dispose();
  37911. }
  37912. if (this._opacityTexture) {
  37913. this._opacityTexture.dispose();
  37914. }
  37915. if (this._reflectionTexture) {
  37916. this._reflectionTexture.dispose();
  37917. }
  37918. if (this._emissiveTexture) {
  37919. this._emissiveTexture.dispose();
  37920. }
  37921. if (this._specularTexture) {
  37922. this._specularTexture.dispose();
  37923. }
  37924. if (this._bumpTexture) {
  37925. this._bumpTexture.dispose();
  37926. }
  37927. if (this._lightmapTexture) {
  37928. this._lightmapTexture.dispose();
  37929. }
  37930. if (this._refractionTexture) {
  37931. this._refractionTexture.dispose();
  37932. }
  37933. }
  37934. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37935. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37936. }
  37937. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37938. };
  37939. StandardMaterial.prototype.clone = function (name) {
  37940. var _this = this;
  37941. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37942. result.name = name;
  37943. result.id = name;
  37944. return result;
  37945. };
  37946. StandardMaterial.prototype.serialize = function () {
  37947. return BABYLON.SerializationHelper.Serialize(this);
  37948. };
  37949. // Statics
  37950. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37951. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37952. };
  37953. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37954. get: function () {
  37955. return StandardMaterial._DiffuseTextureEnabled;
  37956. },
  37957. set: function (value) {
  37958. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37959. return;
  37960. }
  37961. StandardMaterial._DiffuseTextureEnabled = value;
  37962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37963. },
  37964. enumerable: true,
  37965. configurable: true
  37966. });
  37967. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37968. get: function () {
  37969. return StandardMaterial._AmbientTextureEnabled;
  37970. },
  37971. set: function (value) {
  37972. if (StandardMaterial._AmbientTextureEnabled === value) {
  37973. return;
  37974. }
  37975. StandardMaterial._AmbientTextureEnabled = value;
  37976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37977. },
  37978. enumerable: true,
  37979. configurable: true
  37980. });
  37981. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37982. get: function () {
  37983. return StandardMaterial._OpacityTextureEnabled;
  37984. },
  37985. set: function (value) {
  37986. if (StandardMaterial._OpacityTextureEnabled === value) {
  37987. return;
  37988. }
  37989. StandardMaterial._OpacityTextureEnabled = value;
  37990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37991. },
  37992. enumerable: true,
  37993. configurable: true
  37994. });
  37995. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37996. get: function () {
  37997. return StandardMaterial._ReflectionTextureEnabled;
  37998. },
  37999. set: function (value) {
  38000. if (StandardMaterial._ReflectionTextureEnabled === value) {
  38001. return;
  38002. }
  38003. StandardMaterial._ReflectionTextureEnabled = value;
  38004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38005. },
  38006. enumerable: true,
  38007. configurable: true
  38008. });
  38009. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  38010. get: function () {
  38011. return StandardMaterial._EmissiveTextureEnabled;
  38012. },
  38013. set: function (value) {
  38014. if (StandardMaterial._EmissiveTextureEnabled === value) {
  38015. return;
  38016. }
  38017. StandardMaterial._EmissiveTextureEnabled = value;
  38018. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38019. },
  38020. enumerable: true,
  38021. configurable: true
  38022. });
  38023. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  38024. get: function () {
  38025. return StandardMaterial._SpecularTextureEnabled;
  38026. },
  38027. set: function (value) {
  38028. if (StandardMaterial._SpecularTextureEnabled === value) {
  38029. return;
  38030. }
  38031. StandardMaterial._SpecularTextureEnabled = value;
  38032. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38033. },
  38034. enumerable: true,
  38035. configurable: true
  38036. });
  38037. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  38038. get: function () {
  38039. return StandardMaterial._BumpTextureEnabled;
  38040. },
  38041. set: function (value) {
  38042. if (StandardMaterial._BumpTextureEnabled === value) {
  38043. return;
  38044. }
  38045. StandardMaterial._BumpTextureEnabled = value;
  38046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  38052. get: function () {
  38053. return StandardMaterial._LightmapTextureEnabled;
  38054. },
  38055. set: function (value) {
  38056. if (StandardMaterial._LightmapTextureEnabled === value) {
  38057. return;
  38058. }
  38059. StandardMaterial._LightmapTextureEnabled = value;
  38060. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38061. },
  38062. enumerable: true,
  38063. configurable: true
  38064. });
  38065. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  38066. get: function () {
  38067. return StandardMaterial._RefractionTextureEnabled;
  38068. },
  38069. set: function (value) {
  38070. if (StandardMaterial._RefractionTextureEnabled === value) {
  38071. return;
  38072. }
  38073. StandardMaterial._RefractionTextureEnabled = value;
  38074. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38075. },
  38076. enumerable: true,
  38077. configurable: true
  38078. });
  38079. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  38080. get: function () {
  38081. return StandardMaterial._ColorGradingTextureEnabled;
  38082. },
  38083. set: function (value) {
  38084. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  38085. return;
  38086. }
  38087. StandardMaterial._ColorGradingTextureEnabled = value;
  38088. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38089. },
  38090. enumerable: true,
  38091. configurable: true
  38092. });
  38093. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  38094. get: function () {
  38095. return StandardMaterial._FresnelEnabled;
  38096. },
  38097. set: function (value) {
  38098. if (StandardMaterial._FresnelEnabled === value) {
  38099. return;
  38100. }
  38101. StandardMaterial._FresnelEnabled = value;
  38102. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  38103. },
  38104. enumerable: true,
  38105. configurable: true
  38106. });
  38107. // Flags used to enable or disable a type of texture for all Standard Materials
  38108. StandardMaterial._DiffuseTextureEnabled = true;
  38109. StandardMaterial._AmbientTextureEnabled = true;
  38110. StandardMaterial._OpacityTextureEnabled = true;
  38111. StandardMaterial._ReflectionTextureEnabled = true;
  38112. StandardMaterial._EmissiveTextureEnabled = true;
  38113. StandardMaterial._SpecularTextureEnabled = true;
  38114. StandardMaterial._BumpTextureEnabled = true;
  38115. StandardMaterial._LightmapTextureEnabled = true;
  38116. StandardMaterial._RefractionTextureEnabled = true;
  38117. StandardMaterial._ColorGradingTextureEnabled = true;
  38118. StandardMaterial._FresnelEnabled = true;
  38119. __decorate([
  38120. BABYLON.serializeAsTexture("diffuseTexture")
  38121. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  38122. __decorate([
  38123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  38124. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  38125. __decorate([
  38126. BABYLON.serializeAsTexture("ambientTexture")
  38127. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  38128. __decorate([
  38129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38130. ], StandardMaterial.prototype, "ambientTexture", void 0);
  38131. __decorate([
  38132. BABYLON.serializeAsTexture("opacityTexture")
  38133. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  38134. __decorate([
  38135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  38136. ], StandardMaterial.prototype, "opacityTexture", void 0);
  38137. __decorate([
  38138. BABYLON.serializeAsTexture("reflectionTexture")
  38139. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  38140. __decorate([
  38141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38142. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  38143. __decorate([
  38144. BABYLON.serializeAsTexture("emissiveTexture")
  38145. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  38146. __decorate([
  38147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38148. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  38149. __decorate([
  38150. BABYLON.serializeAsTexture("specularTexture")
  38151. ], StandardMaterial.prototype, "_specularTexture", void 0);
  38152. __decorate([
  38153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38154. ], StandardMaterial.prototype, "specularTexture", void 0);
  38155. __decorate([
  38156. BABYLON.serializeAsTexture("bumpTexture")
  38157. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  38158. __decorate([
  38159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38160. ], StandardMaterial.prototype, "bumpTexture", void 0);
  38161. __decorate([
  38162. BABYLON.serializeAsTexture("lightmapTexture")
  38163. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  38164. __decorate([
  38165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38166. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  38167. __decorate([
  38168. BABYLON.serializeAsTexture("refractionTexture")
  38169. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  38170. __decorate([
  38171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38172. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38173. __decorate([
  38174. BABYLON.serializeAsColor3("ambient")
  38175. ], StandardMaterial.prototype, "ambientColor", void 0);
  38176. __decorate([
  38177. BABYLON.serializeAsColor3("diffuse")
  38178. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38179. __decorate([
  38180. BABYLON.serializeAsColor3("specular")
  38181. ], StandardMaterial.prototype, "specularColor", void 0);
  38182. __decorate([
  38183. BABYLON.serializeAsColor3("emissive")
  38184. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38185. __decorate([
  38186. BABYLON.serialize()
  38187. ], StandardMaterial.prototype, "specularPower", void 0);
  38188. __decorate([
  38189. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38190. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38191. __decorate([
  38192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38193. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38194. __decorate([
  38195. BABYLON.serialize("useEmissiveAsIllumination")
  38196. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38197. __decorate([
  38198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38199. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38200. __decorate([
  38201. BABYLON.serialize("linkEmissiveWithDiffuse")
  38202. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38203. __decorate([
  38204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38205. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38206. __decorate([
  38207. BABYLON.serialize("useSpecularOverAlpha")
  38208. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38209. __decorate([
  38210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38211. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38212. __decorate([
  38213. BABYLON.serialize("useReflectionOverAlpha")
  38214. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38215. __decorate([
  38216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38217. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38218. __decorate([
  38219. BABYLON.serialize("disableLighting")
  38220. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38221. __decorate([
  38222. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38223. ], StandardMaterial.prototype, "disableLighting", void 0);
  38224. __decorate([
  38225. BABYLON.serialize("useParallax")
  38226. ], StandardMaterial.prototype, "_useParallax", void 0);
  38227. __decorate([
  38228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38229. ], StandardMaterial.prototype, "useParallax", void 0);
  38230. __decorate([
  38231. BABYLON.serialize("useParallaxOcclusion")
  38232. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38233. __decorate([
  38234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38235. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38236. __decorate([
  38237. BABYLON.serialize()
  38238. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38239. __decorate([
  38240. BABYLON.serialize("roughness")
  38241. ], StandardMaterial.prototype, "_roughness", void 0);
  38242. __decorate([
  38243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38244. ], StandardMaterial.prototype, "roughness", void 0);
  38245. __decorate([
  38246. BABYLON.serialize()
  38247. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38248. __decorate([
  38249. BABYLON.serialize()
  38250. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38251. __decorate([
  38252. BABYLON.serialize("useLightmapAsShadowmap")
  38253. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38254. __decorate([
  38255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38256. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38257. __decorate([
  38258. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38259. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38260. __decorate([
  38261. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38262. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38263. __decorate([
  38264. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38265. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38266. __decorate([
  38267. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38268. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38269. __decorate([
  38270. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38271. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38272. __decorate([
  38273. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38274. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38275. __decorate([
  38276. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38277. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38278. __decorate([
  38279. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38280. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38281. __decorate([
  38282. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38283. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38284. __decorate([
  38285. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38286. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38287. __decorate([
  38288. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38289. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38290. __decorate([
  38291. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38292. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38293. __decorate([
  38294. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38295. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38296. __decorate([
  38297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38298. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38299. __decorate([
  38300. BABYLON.serialize("maxSimultaneousLights")
  38301. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38302. __decorate([
  38303. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38304. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38305. __decorate([
  38306. BABYLON.serialize("invertNormalMapX")
  38307. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38308. __decorate([
  38309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38310. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38311. __decorate([
  38312. BABYLON.serialize("invertNormalMapY")
  38313. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38314. __decorate([
  38315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38316. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38317. __decorate([
  38318. BABYLON.serialize("twoSidedLighting")
  38319. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38320. __decorate([
  38321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38322. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38323. __decorate([
  38324. BABYLON.serialize()
  38325. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38326. return StandardMaterial;
  38327. }(BABYLON.PushMaterial));
  38328. BABYLON.StandardMaterial = StandardMaterial;
  38329. })(BABYLON || (BABYLON = {}));
  38330. //# sourceMappingURL=babylon.standardMaterial.js.map
  38331. var BABYLON;
  38332. (function (BABYLON) {
  38333. var PBRMaterialDefines = /** @class */ (function (_super) {
  38334. __extends(PBRMaterialDefines, _super);
  38335. function PBRMaterialDefines() {
  38336. var _this = _super.call(this) || this;
  38337. _this.PBR = true;
  38338. _this.MAINUV1 = false;
  38339. _this.MAINUV2 = false;
  38340. _this.UV1 = false;
  38341. _this.UV2 = false;
  38342. _this.ALBEDO = false;
  38343. _this.ALBEDODIRECTUV = 0;
  38344. _this.VERTEXCOLOR = false;
  38345. _this.AMBIENT = false;
  38346. _this.AMBIENTDIRECTUV = 0;
  38347. _this.AMBIENTINGRAYSCALE = false;
  38348. _this.OPACITY = false;
  38349. _this.VERTEXALPHA = false;
  38350. _this.OPACITYDIRECTUV = 0;
  38351. _this.OPACITYRGB = false;
  38352. _this.ALPHATEST = false;
  38353. _this.DEPTHPREPASS = false;
  38354. _this.ALPHABLEND = false;
  38355. _this.ALPHAFROMALBEDO = false;
  38356. _this.ALPHATESTVALUE = 0.5;
  38357. _this.SPECULAROVERALPHA = false;
  38358. _this.RADIANCEOVERALPHA = false;
  38359. _this.ALPHAFRESNEL = false;
  38360. _this.LINEARALPHAFRESNEL = false;
  38361. _this.PREMULTIPLYALPHA = false;
  38362. _this.EMISSIVE = false;
  38363. _this.EMISSIVEDIRECTUV = 0;
  38364. _this.REFLECTIVITY = false;
  38365. _this.REFLECTIVITYDIRECTUV = 0;
  38366. _this.SPECULARTERM = false;
  38367. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38368. _this.MICROSURFACEAUTOMATIC = false;
  38369. _this.LODBASEDMICROSFURACE = false;
  38370. _this.MICROSURFACEMAP = false;
  38371. _this.MICROSURFACEMAPDIRECTUV = 0;
  38372. _this.METALLICWORKFLOW = false;
  38373. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38374. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38375. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38376. _this.AOSTOREINMETALMAPRED = false;
  38377. _this.ENVIRONMENTBRDF = false;
  38378. _this.NORMAL = false;
  38379. _this.TANGENT = false;
  38380. _this.BUMP = false;
  38381. _this.BUMPDIRECTUV = 0;
  38382. _this.PARALLAX = false;
  38383. _this.PARALLAXOCCLUSION = false;
  38384. _this.NORMALXYSCALE = true;
  38385. _this.LIGHTMAP = false;
  38386. _this.LIGHTMAPDIRECTUV = 0;
  38387. _this.USELIGHTMAPASSHADOWMAP = false;
  38388. _this.REFLECTION = false;
  38389. _this.REFLECTIONMAP_3D = false;
  38390. _this.REFLECTIONMAP_SPHERICAL = false;
  38391. _this.REFLECTIONMAP_PLANAR = false;
  38392. _this.REFLECTIONMAP_CUBIC = false;
  38393. _this.REFLECTIONMAP_PROJECTION = false;
  38394. _this.REFLECTIONMAP_SKYBOX = false;
  38395. _this.REFLECTIONMAP_EXPLICIT = false;
  38396. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38397. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38398. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38399. _this.INVERTCUBICMAP = false;
  38400. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38401. _this.USESPHERICALINVERTEX = false;
  38402. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38403. _this.LODINREFLECTIONALPHA = false;
  38404. _this.GAMMAREFLECTION = false;
  38405. _this.RADIANCEOCCLUSION = false;
  38406. _this.HORIZONOCCLUSION = false;
  38407. _this.REFRACTION = false;
  38408. _this.REFRACTIONMAP_3D = false;
  38409. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38410. _this.LODINREFRACTIONALPHA = false;
  38411. _this.GAMMAREFRACTION = false;
  38412. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38413. _this.INSTANCES = false;
  38414. _this.NUM_BONE_INFLUENCERS = 0;
  38415. _this.BonesPerMesh = 0;
  38416. _this.NONUNIFORMSCALING = false;
  38417. _this.MORPHTARGETS = false;
  38418. _this.MORPHTARGETS_NORMAL = false;
  38419. _this.MORPHTARGETS_TANGENT = false;
  38420. _this.NUM_MORPH_INFLUENCERS = 0;
  38421. _this.IMAGEPROCESSING = false;
  38422. _this.VIGNETTE = false;
  38423. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38424. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38425. _this.TONEMAPPING = false;
  38426. _this.CONTRAST = false;
  38427. _this.COLORCURVES = false;
  38428. _this.COLORGRADING = false;
  38429. _this.COLORGRADING3D = false;
  38430. _this.SAMPLER3DGREENDEPTH = false;
  38431. _this.SAMPLER3DBGRMAP = false;
  38432. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38433. _this.EXPOSURE = false;
  38434. _this.USEPHYSICALLIGHTFALLOFF = false;
  38435. _this.TWOSIDEDLIGHTING = false;
  38436. _this.SHADOWFLOAT = false;
  38437. _this.CLIPPLANE = false;
  38438. _this.POINTSIZE = false;
  38439. _this.FOG = false;
  38440. _this.LOGARITHMICDEPTH = false;
  38441. _this.FORCENORMALFORWARD = false;
  38442. _this.rebuild();
  38443. return _this;
  38444. }
  38445. PBRMaterialDefines.prototype.reset = function () {
  38446. _super.prototype.reset.call(this);
  38447. this.ALPHATESTVALUE = 0.5;
  38448. this.PBR = true;
  38449. };
  38450. return PBRMaterialDefines;
  38451. }(BABYLON.MaterialDefines));
  38452. /**
  38453. * The Physically based material base class of BJS.
  38454. *
  38455. * This offers the main features of a standard PBR material.
  38456. * For more information, please refer to the documentation :
  38457. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38458. */
  38459. var PBRBaseMaterial = /** @class */ (function (_super) {
  38460. __extends(PBRBaseMaterial, _super);
  38461. /**
  38462. * Instantiates a new PBRMaterial instance.
  38463. *
  38464. * @param name The material name
  38465. * @param scene The scene the material will be use in.
  38466. */
  38467. function PBRBaseMaterial(name, scene) {
  38468. var _this = _super.call(this, name, scene) || this;
  38469. /**
  38470. * Intensity of the direct lights e.g. the four lights available in your scene.
  38471. * This impacts both the direct diffuse and specular highlights.
  38472. */
  38473. _this._directIntensity = 1.0;
  38474. /**
  38475. * Intensity of the emissive part of the material.
  38476. * This helps controlling the emissive effect without modifying the emissive color.
  38477. */
  38478. _this._emissiveIntensity = 1.0;
  38479. /**
  38480. * Intensity of the environment e.g. how much the environment will light the object
  38481. * either through harmonics for rough material or through the refelction for shiny ones.
  38482. */
  38483. _this._environmentIntensity = 1.0;
  38484. /**
  38485. * This is a special control allowing the reduction of the specular highlights coming from the
  38486. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38487. */
  38488. _this._specularIntensity = 1.0;
  38489. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38490. /**
  38491. * Debug Control allowing disabling the bump map on this material.
  38492. */
  38493. _this._disableBumpMap = false;
  38494. /**
  38495. * AKA Occlusion Texture Intensity in other nomenclature.
  38496. */
  38497. _this._ambientTextureStrength = 1.0;
  38498. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38499. /**
  38500. * AKA Diffuse Color in other nomenclature.
  38501. */
  38502. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38503. /**
  38504. * AKA Specular Color in other nomenclature.
  38505. */
  38506. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38507. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38508. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38509. /**
  38510. * AKA Glossiness in other nomenclature.
  38511. */
  38512. _this._microSurface = 0.9;
  38513. /**
  38514. * source material index of refraction (IOR)' / 'destination material IOR.
  38515. */
  38516. _this._indexOfRefraction = 0.66;
  38517. /**
  38518. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38519. */
  38520. _this._invertRefractionY = false;
  38521. /**
  38522. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38523. * Materials half opaque for instance using refraction could benefit from this control.
  38524. */
  38525. _this._linkRefractionWithTransparency = false;
  38526. _this._useLightmapAsShadowmap = false;
  38527. /**
  38528. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38529. * makes the reflect vector face the model (under horizon).
  38530. */
  38531. _this._useHorizonOcclusion = true;
  38532. /**
  38533. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38534. * too much the area relying on ambient texture to define their ambient occlusion.
  38535. */
  38536. _this._useRadianceOcclusion = true;
  38537. /**
  38538. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38539. */
  38540. _this._useAlphaFromAlbedoTexture = false;
  38541. /**
  38542. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38543. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38544. */
  38545. _this._useSpecularOverAlpha = true;
  38546. /**
  38547. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38548. */
  38549. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38550. /**
  38551. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38552. */
  38553. _this._useRoughnessFromMetallicTextureAlpha = true;
  38554. /**
  38555. * Specifies if the metallic texture contains the roughness information in its green channel.
  38556. */
  38557. _this._useRoughnessFromMetallicTextureGreen = false;
  38558. /**
  38559. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38560. */
  38561. _this._useMetallnessFromMetallicTextureBlue = false;
  38562. /**
  38563. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38564. */
  38565. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38566. /**
  38567. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38568. */
  38569. _this._useAmbientInGrayScale = false;
  38570. /**
  38571. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38572. * The material will try to infer what glossiness each pixel should be.
  38573. */
  38574. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38575. /**
  38576. * BJS is using an harcoded light falloff based on a manually sets up range.
  38577. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38578. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38579. */
  38580. _this._usePhysicalLightFalloff = true;
  38581. /**
  38582. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38583. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38584. */
  38585. _this._useRadianceOverAlpha = true;
  38586. /**
  38587. * Allows using the bump map in parallax mode.
  38588. */
  38589. _this._useParallax = false;
  38590. /**
  38591. * Allows using the bump map in parallax occlusion mode.
  38592. */
  38593. _this._useParallaxOcclusion = false;
  38594. /**
  38595. * Controls the scale bias of the parallax mode.
  38596. */
  38597. _this._parallaxScaleBias = 0.05;
  38598. /**
  38599. * If sets to true, disables all the lights affecting the material.
  38600. */
  38601. _this._disableLighting = false;
  38602. /**
  38603. * Number of Simultaneous lights allowed on the material.
  38604. */
  38605. _this._maxSimultaneousLights = 4;
  38606. /**
  38607. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38608. */
  38609. _this._invertNormalMapX = false;
  38610. /**
  38611. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38612. */
  38613. _this._invertNormalMapY = false;
  38614. /**
  38615. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38616. */
  38617. _this._twoSidedLighting = false;
  38618. /**
  38619. * Defines the alpha limits in alpha test mode.
  38620. */
  38621. _this._alphaCutOff = 0.4;
  38622. /**
  38623. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38624. */
  38625. _this._forceAlphaTest = false;
  38626. /**
  38627. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38628. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38629. */
  38630. _this._useAlphaFresnel = false;
  38631. /**
  38632. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38633. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38634. */
  38635. _this._useLinearAlphaFresnel = false;
  38636. /**
  38637. * The transparency mode of the material.
  38638. */
  38639. _this._transparencyMode = null;
  38640. /**
  38641. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38642. * from cos thetav and roughness:
  38643. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38644. */
  38645. _this._environmentBRDFTexture = null;
  38646. /**
  38647. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38648. */
  38649. _this._forceIrradianceInFragment = false;
  38650. /**
  38651. * Force normal to face away from face.
  38652. */
  38653. _this._forceNormalForward = false;
  38654. /**
  38655. * Force metallic workflow.
  38656. */
  38657. _this._forceMetallicWorkflow = false;
  38658. _this._renderTargets = new BABYLON.SmartArray(16);
  38659. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38660. // Setup the default processing configuration to the scene.
  38661. _this._attachImageProcessingConfiguration(null);
  38662. _this.getRenderTargetTextures = function () {
  38663. _this._renderTargets.reset();
  38664. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38665. _this._renderTargets.push(_this._reflectionTexture);
  38666. }
  38667. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38668. _this._renderTargets.push(_this._refractionTexture);
  38669. }
  38670. return _this._renderTargets;
  38671. };
  38672. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38673. return _this;
  38674. }
  38675. /**
  38676. * Attaches a new image processing configuration to the PBR Material.
  38677. * @param configuration
  38678. */
  38679. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38680. var _this = this;
  38681. if (configuration === this._imageProcessingConfiguration) {
  38682. return;
  38683. }
  38684. // Detaches observer.
  38685. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38686. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38687. }
  38688. // Pick the scene configuration if needed.
  38689. if (!configuration) {
  38690. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38691. }
  38692. else {
  38693. this._imageProcessingConfiguration = configuration;
  38694. }
  38695. // Attaches observer.
  38696. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38697. _this._markAllSubMeshesAsImageProcessingDirty();
  38698. });
  38699. };
  38700. PBRBaseMaterial.prototype.getClassName = function () {
  38701. return "PBRBaseMaterial";
  38702. };
  38703. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38704. get: function () {
  38705. return this._useLogarithmicDepth;
  38706. },
  38707. set: function (value) {
  38708. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38714. /**
  38715. * Gets the current transparency mode.
  38716. */
  38717. get: function () {
  38718. return this._transparencyMode;
  38719. },
  38720. /**
  38721. * Sets the transparency mode of the material.
  38722. */
  38723. set: function (value) {
  38724. if (this._transparencyMode === value) {
  38725. return;
  38726. }
  38727. this._transparencyMode = value;
  38728. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38729. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38730. },
  38731. enumerable: true,
  38732. configurable: true
  38733. });
  38734. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38735. /**
  38736. * Returns true if alpha blending should be disabled.
  38737. */
  38738. get: function () {
  38739. return (this._linkRefractionWithTransparency ||
  38740. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38741. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38742. },
  38743. enumerable: true,
  38744. configurable: true
  38745. });
  38746. /**
  38747. * Specifies whether or not this material should be rendered in alpha blend mode.
  38748. */
  38749. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38750. if (this._disableAlphaBlending) {
  38751. return false;
  38752. }
  38753. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38754. };
  38755. /**
  38756. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38757. */
  38758. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38759. if (this._disableAlphaBlending) {
  38760. return false;
  38761. }
  38762. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38763. };
  38764. /**
  38765. * Specifies whether or not this material should be rendered in alpha test mode.
  38766. */
  38767. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38768. if (this._forceAlphaTest) {
  38769. return true;
  38770. }
  38771. if (this._linkRefractionWithTransparency) {
  38772. return false;
  38773. }
  38774. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38775. };
  38776. /**
  38777. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38778. */
  38779. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38780. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38781. };
  38782. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38783. return this._albedoTexture;
  38784. };
  38785. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38786. var _this = this;
  38787. if (subMesh.effect && this.isFrozen) {
  38788. if (this._wasPreviouslyReady) {
  38789. return true;
  38790. }
  38791. }
  38792. if (!subMesh._materialDefines) {
  38793. subMesh._materialDefines = new PBRMaterialDefines();
  38794. }
  38795. var scene = this.getScene();
  38796. var defines = subMesh._materialDefines;
  38797. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38798. if (defines._renderId === scene.getRenderId()) {
  38799. return true;
  38800. }
  38801. }
  38802. var engine = scene.getEngine();
  38803. // Lights
  38804. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38805. defines._needNormals = true;
  38806. // Textures
  38807. if (defines._areTexturesDirty) {
  38808. defines._needUVs = false;
  38809. if (scene.texturesEnabled) {
  38810. if (scene.getEngine().getCaps().textureLOD) {
  38811. defines.LODBASEDMICROSFURACE = true;
  38812. }
  38813. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38814. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38815. return false;
  38816. }
  38817. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38818. }
  38819. else {
  38820. defines.ALBEDO = false;
  38821. }
  38822. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38823. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38824. return false;
  38825. }
  38826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38827. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38828. }
  38829. else {
  38830. defines.AMBIENT = false;
  38831. }
  38832. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38833. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38834. return false;
  38835. }
  38836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38837. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38838. }
  38839. else {
  38840. defines.OPACITY = false;
  38841. }
  38842. var reflectionTexture = this._getReflectionTexture();
  38843. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38844. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38845. return false;
  38846. }
  38847. defines.REFLECTION = true;
  38848. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38849. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38850. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38851. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38852. defines.INVERTCUBICMAP = true;
  38853. }
  38854. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38855. switch (reflectionTexture.coordinatesMode) {
  38856. case BABYLON.Texture.CUBIC_MODE:
  38857. case BABYLON.Texture.INVCUBIC_MODE:
  38858. defines.REFLECTIONMAP_CUBIC = true;
  38859. break;
  38860. case BABYLON.Texture.EXPLICIT_MODE:
  38861. defines.REFLECTIONMAP_EXPLICIT = true;
  38862. break;
  38863. case BABYLON.Texture.PLANAR_MODE:
  38864. defines.REFLECTIONMAP_PLANAR = true;
  38865. break;
  38866. case BABYLON.Texture.PROJECTION_MODE:
  38867. defines.REFLECTIONMAP_PROJECTION = true;
  38868. break;
  38869. case BABYLON.Texture.SKYBOX_MODE:
  38870. defines.REFLECTIONMAP_SKYBOX = true;
  38871. break;
  38872. case BABYLON.Texture.SPHERICAL_MODE:
  38873. defines.REFLECTIONMAP_SPHERICAL = true;
  38874. break;
  38875. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38876. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38877. break;
  38878. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38879. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38880. break;
  38881. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38882. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38883. break;
  38884. }
  38885. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38886. if (reflectionTexture.sphericalPolynomial) {
  38887. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38888. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38889. defines.USESPHERICALINVERTEX = false;
  38890. }
  38891. else {
  38892. defines.USESPHERICALINVERTEX = true;
  38893. }
  38894. }
  38895. }
  38896. }
  38897. else {
  38898. defines.REFLECTION = false;
  38899. defines.REFLECTIONMAP_3D = false;
  38900. defines.REFLECTIONMAP_SPHERICAL = false;
  38901. defines.REFLECTIONMAP_PLANAR = false;
  38902. defines.REFLECTIONMAP_CUBIC = false;
  38903. defines.REFLECTIONMAP_PROJECTION = false;
  38904. defines.REFLECTIONMAP_SKYBOX = false;
  38905. defines.REFLECTIONMAP_EXPLICIT = false;
  38906. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38907. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38908. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38909. defines.INVERTCUBICMAP = false;
  38910. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38911. defines.USESPHERICALINVERTEX = false;
  38912. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38913. defines.LODINREFLECTIONALPHA = false;
  38914. defines.GAMMAREFLECTION = false;
  38915. }
  38916. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38917. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38918. return false;
  38919. }
  38920. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38921. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38922. }
  38923. else {
  38924. defines.LIGHTMAP = false;
  38925. }
  38926. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38927. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38928. return false;
  38929. }
  38930. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38931. }
  38932. else {
  38933. defines.EMISSIVE = false;
  38934. }
  38935. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38936. if (this._metallicTexture) {
  38937. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38938. return false;
  38939. }
  38940. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38941. defines.METALLICWORKFLOW = true;
  38942. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38943. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38944. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38945. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38946. }
  38947. else if (this._reflectivityTexture) {
  38948. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38949. return false;
  38950. }
  38951. defines.METALLICWORKFLOW = false;
  38952. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38953. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38954. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38955. }
  38956. else {
  38957. defines.METALLICWORKFLOW = false;
  38958. defines.REFLECTIVITY = false;
  38959. }
  38960. if (this._microSurfaceTexture) {
  38961. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38962. return false;
  38963. }
  38964. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38965. }
  38966. else {
  38967. defines.MICROSURFACEMAP = false;
  38968. }
  38969. }
  38970. else {
  38971. defines.REFLECTIVITY = false;
  38972. defines.MICROSURFACEMAP = false;
  38973. }
  38974. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38975. // Bump texure can not be none blocking.
  38976. if (!this._bumpTexture.isReady()) {
  38977. return false;
  38978. }
  38979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38980. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38981. defines.PARALLAX = true;
  38982. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38983. }
  38984. else {
  38985. defines.PARALLAX = false;
  38986. }
  38987. }
  38988. else {
  38989. defines.BUMP = false;
  38990. }
  38991. var refractionTexture = this._getRefractionTexture();
  38992. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38993. if (!refractionTexture.isReadyOrNotBlocking()) {
  38994. return false;
  38995. }
  38996. defines.REFRACTION = true;
  38997. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38998. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38999. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  39000. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  39001. if (this._linkRefractionWithTransparency) {
  39002. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  39003. }
  39004. }
  39005. else {
  39006. defines.REFRACTION = false;
  39007. }
  39008. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39009. // This is blocking.
  39010. if (!this._environmentBRDFTexture.isReady()) {
  39011. return false;
  39012. }
  39013. defines.ENVIRONMENTBRDF = true;
  39014. }
  39015. else {
  39016. defines.ENVIRONMENTBRDF = false;
  39017. }
  39018. if (this._shouldUseAlphaFromAlbedoTexture()) {
  39019. defines.ALPHAFROMALBEDO = true;
  39020. }
  39021. else {
  39022. defines.ALPHAFROMALBEDO = false;
  39023. }
  39024. }
  39025. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39026. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  39027. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  39028. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  39029. defines.METALLICWORKFLOW = true;
  39030. }
  39031. else {
  39032. defines.METALLICWORKFLOW = false;
  39033. }
  39034. if (!this.backFaceCulling && this._twoSidedLighting) {
  39035. defines.TWOSIDEDLIGHTING = true;
  39036. }
  39037. else {
  39038. defines.TWOSIDEDLIGHTING = false;
  39039. }
  39040. defines.ALPHATESTVALUE = this._alphaCutOff;
  39041. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39042. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  39043. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  39044. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  39045. }
  39046. if (defines._areImageProcessingDirty) {
  39047. if (!this._imageProcessingConfiguration.isReady()) {
  39048. return false;
  39049. }
  39050. this._imageProcessingConfiguration.prepareDefines(defines);
  39051. }
  39052. defines.FORCENORMALFORWARD = this._forceNormalForward;
  39053. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  39054. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  39055. // Misc.
  39056. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  39057. // Values that need to be evaluated on every frame
  39058. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  39059. // Attribs
  39060. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  39061. var bufferMesh = null;
  39062. if (mesh instanceof BABYLON.InstancedMesh) {
  39063. bufferMesh = mesh.sourceMesh;
  39064. }
  39065. else if (mesh instanceof BABYLON.Mesh) {
  39066. bufferMesh = mesh;
  39067. }
  39068. if (bufferMesh) {
  39069. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39070. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  39071. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  39072. var normals = normalVertexBuffer.getData();
  39073. var vertexBufferOffset = normalVertexBuffer.getOffset();
  39074. var strideSize = normalVertexBuffer.getStrideSize();
  39075. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  39076. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  39077. defines.NORMAL = false;
  39078. }
  39079. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39080. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  39081. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  39082. var tangents = tangentVertexBuffer.getData();
  39083. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  39084. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  39085. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  39086. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  39087. defines.TANGENT = false;
  39088. }
  39089. }
  39090. }
  39091. else {
  39092. if (!scene.getEngine().getCaps().standardDerivatives) {
  39093. bufferMesh.createNormals(true);
  39094. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  39095. }
  39096. }
  39097. }
  39098. }
  39099. // Get correct effect
  39100. if (defines.isDirty) {
  39101. defines.markAsProcessed();
  39102. scene.resetCachedMaterial();
  39103. // Fallbacks
  39104. var fallbacks = new BABYLON.EffectFallbacks();
  39105. var fallbackRank = 0;
  39106. if (defines.USESPHERICALINVERTEX) {
  39107. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  39108. }
  39109. if (defines.FOG) {
  39110. fallbacks.addFallback(fallbackRank, "FOG");
  39111. }
  39112. if (defines.POINTSIZE) {
  39113. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  39114. }
  39115. if (defines.LOGARITHMICDEPTH) {
  39116. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  39117. }
  39118. if (defines.PARALLAX) {
  39119. fallbacks.addFallback(fallbackRank, "PARALLAX");
  39120. }
  39121. if (defines.PARALLAXOCCLUSION) {
  39122. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  39123. }
  39124. if (defines.ENVIRONMENTBRDF) {
  39125. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  39126. }
  39127. if (defines.TANGENT) {
  39128. fallbacks.addFallback(fallbackRank++, "TANGENT");
  39129. }
  39130. if (defines.BUMP) {
  39131. fallbacks.addFallback(fallbackRank++, "BUMP");
  39132. }
  39133. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  39134. if (defines.SPECULARTERM) {
  39135. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  39136. }
  39137. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  39138. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  39139. }
  39140. if (defines.LIGHTMAP) {
  39141. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  39142. }
  39143. if (defines.NORMAL) {
  39144. fallbacks.addFallback(fallbackRank++, "NORMAL");
  39145. }
  39146. if (defines.AMBIENT) {
  39147. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  39148. }
  39149. if (defines.EMISSIVE) {
  39150. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  39151. }
  39152. if (defines.VERTEXCOLOR) {
  39153. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  39154. }
  39155. if (defines.NUM_BONE_INFLUENCERS > 0) {
  39156. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  39157. }
  39158. if (defines.MORPHTARGETS) {
  39159. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  39160. }
  39161. //Attributes
  39162. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39163. if (defines.NORMAL) {
  39164. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39165. }
  39166. if (defines.TANGENT) {
  39167. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39168. }
  39169. if (defines.UV1) {
  39170. attribs.push(BABYLON.VertexBuffer.UVKind);
  39171. }
  39172. if (defines.UV2) {
  39173. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39174. }
  39175. if (defines.VERTEXCOLOR) {
  39176. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39177. }
  39178. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39179. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39180. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39181. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39182. "vFogInfos", "vFogColor", "pointSize",
  39183. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39184. "mBones",
  39185. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39186. "vLightingIntensity",
  39187. "logarithmicDepthConstant",
  39188. "vSphericalX", "vSphericalY", "vSphericalZ",
  39189. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39190. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39191. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39192. "vTangentSpaceParams"
  39193. ];
  39194. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39195. "bumpSampler", "lightmapSampler", "opacitySampler",
  39196. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39197. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39198. "microSurfaceSampler", "environmentBrdfSampler"];
  39199. var uniformBuffers = ["Material", "Scene"];
  39200. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39201. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39202. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39203. uniformsNames: uniforms,
  39204. uniformBuffersNames: uniformBuffers,
  39205. samplers: samplers,
  39206. defines: defines,
  39207. maxSimultaneousLights: this._maxSimultaneousLights
  39208. });
  39209. var onCompiled = function (effect) {
  39210. if (_this.onCompiled) {
  39211. _this.onCompiled(effect);
  39212. }
  39213. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39214. };
  39215. var join = defines.toString();
  39216. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39217. attributes: attribs,
  39218. uniformsNames: uniforms,
  39219. uniformBuffersNames: uniformBuffers,
  39220. samplers: samplers,
  39221. defines: join,
  39222. fallbacks: fallbacks,
  39223. onCompiled: onCompiled,
  39224. onError: this.onError,
  39225. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39226. }, engine), defines);
  39227. this.buildUniformLayout();
  39228. }
  39229. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39230. return false;
  39231. }
  39232. defines._renderId = scene.getRenderId();
  39233. this._wasPreviouslyReady = true;
  39234. return true;
  39235. };
  39236. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39237. // Order is important !
  39238. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39239. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39240. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39241. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39242. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39243. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39244. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39245. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39246. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39247. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39248. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39249. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39250. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39251. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39252. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39253. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39254. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39255. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39256. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39257. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39258. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39259. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39260. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39261. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39262. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39263. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39264. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39265. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39266. this._uniformBuffer.addUniform("pointSize", 1);
  39267. this._uniformBuffer.create();
  39268. };
  39269. PBRBaseMaterial.prototype.unbind = function () {
  39270. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39271. this._uniformBuffer.setTexture("reflectionSampler", null);
  39272. }
  39273. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39274. this._uniformBuffer.setTexture("refractionSampler", null);
  39275. }
  39276. _super.prototype.unbind.call(this);
  39277. };
  39278. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39279. this._activeEffect.setMatrix("world", world);
  39280. };
  39281. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39282. var scene = this.getScene();
  39283. var defines = subMesh._materialDefines;
  39284. if (!defines) {
  39285. return;
  39286. }
  39287. var effect = subMesh.effect;
  39288. if (!effect) {
  39289. return;
  39290. }
  39291. this._activeEffect = effect;
  39292. // Matrices
  39293. this.bindOnlyWorldMatrix(world);
  39294. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39295. // Bones
  39296. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39297. var reflectionTexture = null;
  39298. if (mustRebind) {
  39299. this._uniformBuffer.bindToEffect(effect, "Material");
  39300. this.bindViewProjection(effect);
  39301. reflectionTexture = this._getReflectionTexture();
  39302. var refractionTexture = this._getRefractionTexture();
  39303. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39304. // Texture uniforms
  39305. if (scene.texturesEnabled) {
  39306. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39307. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39308. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39309. }
  39310. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39311. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39312. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39313. }
  39314. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39315. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39316. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39317. }
  39318. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39319. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39320. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39321. var polynomials = reflectionTexture.sphericalPolynomial;
  39322. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39323. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39324. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39325. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39326. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39327. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39328. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39329. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39330. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39331. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39332. }
  39333. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39334. }
  39335. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39336. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39337. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39338. }
  39339. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39340. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39341. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39342. }
  39343. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39344. if (this._metallicTexture) {
  39345. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39346. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39347. }
  39348. else if (this._reflectivityTexture) {
  39349. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39350. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39351. }
  39352. if (this._microSurfaceTexture) {
  39353. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39354. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39355. }
  39356. }
  39357. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39358. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39359. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39360. if (scene._mirroredCameraPosition) {
  39361. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39362. }
  39363. else {
  39364. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39365. }
  39366. }
  39367. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39368. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39369. var depth = 1.0;
  39370. if (!refractionTexture.isCube) {
  39371. if (refractionTexture.depth) {
  39372. depth = refractionTexture.depth;
  39373. }
  39374. }
  39375. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39376. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39377. }
  39378. }
  39379. // Point size
  39380. if (this.pointsCloud) {
  39381. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39382. }
  39383. // Colors
  39384. if (defines.METALLICWORKFLOW) {
  39385. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39386. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39387. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39388. }
  39389. else {
  39390. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39391. }
  39392. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39393. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39394. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39395. // Misc
  39396. this._lightingInfos.x = this._directIntensity;
  39397. this._lightingInfos.y = this._emissiveIntensity;
  39398. this._lightingInfos.z = this._environmentIntensity;
  39399. this._lightingInfos.w = this._specularIntensity;
  39400. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39401. }
  39402. // Textures
  39403. if (scene.texturesEnabled) {
  39404. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39405. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39406. }
  39407. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39408. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39409. }
  39410. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39411. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39412. }
  39413. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39414. if (defines.LODBASEDMICROSFURACE) {
  39415. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39416. }
  39417. else {
  39418. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39419. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39420. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39421. }
  39422. }
  39423. if (defines.ENVIRONMENTBRDF) {
  39424. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39425. }
  39426. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39427. if (defines.LODBASEDMICROSFURACE) {
  39428. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39429. }
  39430. else {
  39431. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39432. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39433. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39434. }
  39435. }
  39436. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39437. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39438. }
  39439. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39440. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39441. }
  39442. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39443. if (this._metallicTexture) {
  39444. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39445. }
  39446. else if (this._reflectivityTexture) {
  39447. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39448. }
  39449. if (this._microSurfaceTexture) {
  39450. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39451. }
  39452. }
  39453. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39454. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39455. }
  39456. }
  39457. // Clip plane
  39458. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39459. // Colors
  39460. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39461. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39462. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39463. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39464. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39465. }
  39466. if (mustRebind || !this.isFrozen) {
  39467. // Lights
  39468. if (scene.lightsEnabled && !this._disableLighting) {
  39469. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39470. }
  39471. // View
  39472. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39473. this.bindView(effect);
  39474. }
  39475. // Fog
  39476. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39477. // Morph targets
  39478. if (defines.NUM_MORPH_INFLUENCERS) {
  39479. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39480. }
  39481. // image processing
  39482. this._imageProcessingConfiguration.bind(this._activeEffect);
  39483. // Log. depth
  39484. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39485. }
  39486. this._uniformBuffer.update();
  39487. this._afterBind(mesh);
  39488. };
  39489. PBRBaseMaterial.prototype.getAnimatables = function () {
  39490. var results = [];
  39491. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39492. results.push(this._albedoTexture);
  39493. }
  39494. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39495. results.push(this._ambientTexture);
  39496. }
  39497. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39498. results.push(this._opacityTexture);
  39499. }
  39500. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39501. results.push(this._reflectionTexture);
  39502. }
  39503. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39504. results.push(this._emissiveTexture);
  39505. }
  39506. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39507. results.push(this._metallicTexture);
  39508. }
  39509. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39510. results.push(this._reflectivityTexture);
  39511. }
  39512. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39513. results.push(this._bumpTexture);
  39514. }
  39515. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39516. results.push(this._lightmapTexture);
  39517. }
  39518. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39519. results.push(this._refractionTexture);
  39520. }
  39521. return results;
  39522. };
  39523. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39524. if (this._reflectionTexture) {
  39525. return this._reflectionTexture;
  39526. }
  39527. return this.getScene().environmentTexture;
  39528. };
  39529. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39530. if (this._refractionTexture) {
  39531. return this._refractionTexture;
  39532. }
  39533. if (this._linkRefractionWithTransparency) {
  39534. return this.getScene().environmentTexture;
  39535. }
  39536. return null;
  39537. };
  39538. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39539. if (forceDisposeTextures) {
  39540. if (this._albedoTexture) {
  39541. this._albedoTexture.dispose();
  39542. }
  39543. if (this._ambientTexture) {
  39544. this._ambientTexture.dispose();
  39545. }
  39546. if (this._opacityTexture) {
  39547. this._opacityTexture.dispose();
  39548. }
  39549. if (this._reflectionTexture) {
  39550. this._reflectionTexture.dispose();
  39551. }
  39552. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39553. this._environmentBRDFTexture.dispose();
  39554. }
  39555. if (this._emissiveTexture) {
  39556. this._emissiveTexture.dispose();
  39557. }
  39558. if (this._metallicTexture) {
  39559. this._metallicTexture.dispose();
  39560. }
  39561. if (this._reflectivityTexture) {
  39562. this._reflectivityTexture.dispose();
  39563. }
  39564. if (this._bumpTexture) {
  39565. this._bumpTexture.dispose();
  39566. }
  39567. if (this._lightmapTexture) {
  39568. this._lightmapTexture.dispose();
  39569. }
  39570. if (this._refractionTexture) {
  39571. this._refractionTexture.dispose();
  39572. }
  39573. }
  39574. this._renderTargets.dispose();
  39575. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39576. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39577. }
  39578. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39579. };
  39580. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39581. __decorate([
  39582. BABYLON.serializeAsImageProcessingConfiguration()
  39583. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39584. __decorate([
  39585. BABYLON.serialize()
  39586. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39587. __decorate([
  39588. BABYLON.serialize()
  39589. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39590. return PBRBaseMaterial;
  39591. }(BABYLON.PushMaterial));
  39592. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39593. })(BABYLON || (BABYLON = {}));
  39594. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39595. var BABYLON;
  39596. (function (BABYLON) {
  39597. /**
  39598. * The Physically based simple base material of BJS.
  39599. *
  39600. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39601. * It is used as the base class for both the specGloss and metalRough conventions.
  39602. */
  39603. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39604. __extends(PBRBaseSimpleMaterial, _super);
  39605. /**
  39606. * Instantiates a new PBRMaterial instance.
  39607. *
  39608. * @param name The material name
  39609. * @param scene The scene the material will be use in.
  39610. */
  39611. function PBRBaseSimpleMaterial(name, scene) {
  39612. var _this = _super.call(this, name, scene) || this;
  39613. /**
  39614. * Number of Simultaneous lights allowed on the material.
  39615. */
  39616. _this.maxSimultaneousLights = 4;
  39617. /**
  39618. * If sets to true, disables all the lights affecting the material.
  39619. */
  39620. _this.disableLighting = false;
  39621. /**
  39622. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39623. */
  39624. _this.invertNormalMapX = false;
  39625. /**
  39626. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39627. */
  39628. _this.invertNormalMapY = false;
  39629. /**
  39630. * Emissivie color used to self-illuminate the model.
  39631. */
  39632. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39633. /**
  39634. * Occlusion Channel Strenght.
  39635. */
  39636. _this.occlusionStrength = 1.0;
  39637. _this.useLightmapAsShadowmap = false;
  39638. _this._useAlphaFromAlbedoTexture = true;
  39639. _this._useAmbientInGrayScale = true;
  39640. return _this;
  39641. }
  39642. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39643. /**
  39644. * Gets the current double sided mode.
  39645. */
  39646. get: function () {
  39647. return this._twoSidedLighting;
  39648. },
  39649. /**
  39650. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39651. */
  39652. set: function (value) {
  39653. if (this._twoSidedLighting === value) {
  39654. return;
  39655. }
  39656. this._twoSidedLighting = value;
  39657. this.backFaceCulling = !value;
  39658. this._markAllSubMeshesAsTexturesDirty();
  39659. },
  39660. enumerable: true,
  39661. configurable: true
  39662. });
  39663. /**
  39664. * Return the active textures of the material.
  39665. */
  39666. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39667. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39668. if (this.environmentTexture) {
  39669. activeTextures.push(this.environmentTexture);
  39670. }
  39671. if (this.normalTexture) {
  39672. activeTextures.push(this.normalTexture);
  39673. }
  39674. if (this.emissiveTexture) {
  39675. activeTextures.push(this.emissiveTexture);
  39676. }
  39677. if (this.occlusionTexture) {
  39678. activeTextures.push(this.occlusionTexture);
  39679. }
  39680. if (this.lightmapTexture) {
  39681. activeTextures.push(this.lightmapTexture);
  39682. }
  39683. return activeTextures;
  39684. };
  39685. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39686. if (_super.prototype.hasTexture.call(this, texture)) {
  39687. return true;
  39688. }
  39689. if (this.lightmapTexture === texture) {
  39690. return true;
  39691. }
  39692. return false;
  39693. };
  39694. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39695. return "PBRBaseSimpleMaterial";
  39696. };
  39697. __decorate([
  39698. BABYLON.serialize(),
  39699. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39700. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39701. __decorate([
  39702. BABYLON.serialize(),
  39703. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39704. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39705. __decorate([
  39706. BABYLON.serializeAsTexture(),
  39707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39708. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39709. __decorate([
  39710. BABYLON.serialize(),
  39711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39712. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39713. __decorate([
  39714. BABYLON.serialize(),
  39715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39716. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39717. __decorate([
  39718. BABYLON.serializeAsTexture(),
  39719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39720. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39721. __decorate([
  39722. BABYLON.serializeAsColor3("emissive"),
  39723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39724. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39725. __decorate([
  39726. BABYLON.serializeAsTexture(),
  39727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39728. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39729. __decorate([
  39730. BABYLON.serialize(),
  39731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39732. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39733. __decorate([
  39734. BABYLON.serializeAsTexture(),
  39735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39736. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39737. __decorate([
  39738. BABYLON.serialize(),
  39739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39740. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39741. __decorate([
  39742. BABYLON.serialize()
  39743. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39744. __decorate([
  39745. BABYLON.serializeAsTexture(),
  39746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39747. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39748. __decorate([
  39749. BABYLON.serialize(),
  39750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39751. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39752. return PBRBaseSimpleMaterial;
  39753. }(BABYLON.PBRBaseMaterial));
  39754. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39755. })(BABYLON || (BABYLON = {}));
  39756. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39757. var BABYLON;
  39758. (function (BABYLON) {
  39759. /**
  39760. * The Physically based material of BJS.
  39761. *
  39762. * This offers the main features of a standard PBR material.
  39763. * For more information, please refer to the documentation :
  39764. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39765. */
  39766. var PBRMaterial = /** @class */ (function (_super) {
  39767. __extends(PBRMaterial, _super);
  39768. /**
  39769. * Instantiates a new PBRMaterial instance.
  39770. *
  39771. * @param name The material name
  39772. * @param scene The scene the material will be use in.
  39773. */
  39774. function PBRMaterial(name, scene) {
  39775. var _this = _super.call(this, name, scene) || this;
  39776. /**
  39777. * Intensity of the direct lights e.g. the four lights available in your scene.
  39778. * This impacts both the direct diffuse and specular highlights.
  39779. */
  39780. _this.directIntensity = 1.0;
  39781. /**
  39782. * Intensity of the emissive part of the material.
  39783. * This helps controlling the emissive effect without modifying the emissive color.
  39784. */
  39785. _this.emissiveIntensity = 1.0;
  39786. /**
  39787. * Intensity of the environment e.g. how much the environment will light the object
  39788. * either through harmonics for rough material or through the refelction for shiny ones.
  39789. */
  39790. _this.environmentIntensity = 1.0;
  39791. /**
  39792. * This is a special control allowing the reduction of the specular highlights coming from the
  39793. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39794. */
  39795. _this.specularIntensity = 1.0;
  39796. /**
  39797. * Debug Control allowing disabling the bump map on this material.
  39798. */
  39799. _this.disableBumpMap = false;
  39800. /**
  39801. * AKA Occlusion Texture Intensity in other nomenclature.
  39802. */
  39803. _this.ambientTextureStrength = 1.0;
  39804. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39805. /**
  39806. * AKA Diffuse Color in other nomenclature.
  39807. */
  39808. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39809. /**
  39810. * AKA Specular Color in other nomenclature.
  39811. */
  39812. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39813. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39814. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39815. /**
  39816. * AKA Glossiness in other nomenclature.
  39817. */
  39818. _this.microSurface = 1.0;
  39819. /**
  39820. * source material index of refraction (IOR)' / 'destination material IOR.
  39821. */
  39822. _this.indexOfRefraction = 0.66;
  39823. /**
  39824. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39825. */
  39826. _this.invertRefractionY = false;
  39827. /**
  39828. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39829. * Materials half opaque for instance using refraction could benefit from this control.
  39830. */
  39831. _this.linkRefractionWithTransparency = false;
  39832. _this.useLightmapAsShadowmap = false;
  39833. /**
  39834. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39835. */
  39836. _this.useAlphaFromAlbedoTexture = false;
  39837. /**
  39838. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39839. */
  39840. _this.forceAlphaTest = false;
  39841. /**
  39842. * Defines the alpha limits in alpha test mode.
  39843. */
  39844. _this.alphaCutOff = 0.4;
  39845. /**
  39846. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39847. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39848. */
  39849. _this.useSpecularOverAlpha = true;
  39850. /**
  39851. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39852. */
  39853. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39854. /**
  39855. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39856. */
  39857. _this.useRoughnessFromMetallicTextureAlpha = true;
  39858. /**
  39859. * Specifies if the metallic texture contains the roughness information in its green channel.
  39860. */
  39861. _this.useRoughnessFromMetallicTextureGreen = false;
  39862. /**
  39863. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39864. */
  39865. _this.useMetallnessFromMetallicTextureBlue = false;
  39866. /**
  39867. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39868. */
  39869. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39870. /**
  39871. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39872. */
  39873. _this.useAmbientInGrayScale = false;
  39874. /**
  39875. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39876. * The material will try to infer what glossiness each pixel should be.
  39877. */
  39878. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39879. /**
  39880. * BJS is using an harcoded light falloff based on a manually sets up range.
  39881. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39882. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39883. */
  39884. _this.usePhysicalLightFalloff = true;
  39885. /**
  39886. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39887. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39888. */
  39889. _this.useRadianceOverAlpha = true;
  39890. /**
  39891. * Allows using the bump map in parallax mode.
  39892. */
  39893. _this.useParallax = false;
  39894. /**
  39895. * Allows using the bump map in parallax occlusion mode.
  39896. */
  39897. _this.useParallaxOcclusion = false;
  39898. /**
  39899. * Controls the scale bias of the parallax mode.
  39900. */
  39901. _this.parallaxScaleBias = 0.05;
  39902. /**
  39903. * If sets to true, disables all the lights affecting the material.
  39904. */
  39905. _this.disableLighting = false;
  39906. /**
  39907. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39908. */
  39909. _this.forceIrradianceInFragment = false;
  39910. /**
  39911. * Number of Simultaneous lights allowed on the material.
  39912. */
  39913. _this.maxSimultaneousLights = 4;
  39914. /**
  39915. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39916. */
  39917. _this.invertNormalMapX = false;
  39918. /**
  39919. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39920. */
  39921. _this.invertNormalMapY = false;
  39922. /**
  39923. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39924. */
  39925. _this.twoSidedLighting = false;
  39926. /**
  39927. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39928. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39929. */
  39930. _this.useAlphaFresnel = false;
  39931. /**
  39932. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39933. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39934. */
  39935. _this.useLinearAlphaFresnel = false;
  39936. /**
  39937. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39938. * And/Or occlude the blended part.
  39939. */
  39940. _this.environmentBRDFTexture = null;
  39941. /**
  39942. * Force normal to face away from face.
  39943. */
  39944. _this.forceNormalForward = false;
  39945. /**
  39946. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39947. * makes the reflect vector face the model (under horizon).
  39948. */
  39949. _this.useHorizonOcclusion = true;
  39950. /**
  39951. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39952. * too much the area relying on ambient texture to define their ambient occlusion.
  39953. */
  39954. _this.useRadianceOcclusion = true;
  39955. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39956. return _this;
  39957. }
  39958. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39959. /**
  39960. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39961. */
  39962. get: function () {
  39963. return this._PBRMATERIAL_OPAQUE;
  39964. },
  39965. enumerable: true,
  39966. configurable: true
  39967. });
  39968. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39969. /**
  39970. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39971. */
  39972. get: function () {
  39973. return this._PBRMATERIAL_ALPHATEST;
  39974. },
  39975. enumerable: true,
  39976. configurable: true
  39977. });
  39978. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39979. /**
  39980. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39981. */
  39982. get: function () {
  39983. return this._PBRMATERIAL_ALPHABLEND;
  39984. },
  39985. enumerable: true,
  39986. configurable: true
  39987. });
  39988. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39989. /**
  39990. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39991. * They are also discarded below the alpha cutoff threshold to improve performances.
  39992. */
  39993. get: function () {
  39994. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39995. },
  39996. enumerable: true,
  39997. configurable: true
  39998. });
  39999. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  40000. /**
  40001. * Gets the image processing configuration used either in this material.
  40002. */
  40003. get: function () {
  40004. return this._imageProcessingConfiguration;
  40005. },
  40006. /**
  40007. * Sets the Default image processing configuration used either in the this material.
  40008. *
  40009. * If sets to null, the scene one is in use.
  40010. */
  40011. set: function (value) {
  40012. this._attachImageProcessingConfiguration(value);
  40013. // Ensure the effect will be rebuilt.
  40014. this._markAllSubMeshesAsTexturesDirty();
  40015. },
  40016. enumerable: true,
  40017. configurable: true
  40018. });
  40019. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  40020. /**
  40021. * Gets wether the color curves effect is enabled.
  40022. */
  40023. get: function () {
  40024. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40025. },
  40026. /**
  40027. * Sets wether the color curves effect is enabled.
  40028. */
  40029. set: function (value) {
  40030. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40031. },
  40032. enumerable: true,
  40033. configurable: true
  40034. });
  40035. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  40036. /**
  40037. * Gets wether the color grading effect is enabled.
  40038. */
  40039. get: function () {
  40040. return this.imageProcessingConfiguration.colorGradingEnabled;
  40041. },
  40042. /**
  40043. * Gets wether the color grading effect is enabled.
  40044. */
  40045. set: function (value) {
  40046. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40047. },
  40048. enumerable: true,
  40049. configurable: true
  40050. });
  40051. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  40052. /**
  40053. * Gets wether tonemapping is enabled or not.
  40054. */
  40055. get: function () {
  40056. return this._imageProcessingConfiguration.toneMappingEnabled;
  40057. },
  40058. /**
  40059. * Sets wether tonemapping is enabled or not
  40060. */
  40061. set: function (value) {
  40062. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40063. },
  40064. enumerable: true,
  40065. configurable: true
  40066. });
  40067. ;
  40068. ;
  40069. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  40070. /**
  40071. * The camera exposure used on this material.
  40072. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40073. * This corresponds to a photographic exposure.
  40074. */
  40075. get: function () {
  40076. return this._imageProcessingConfiguration.exposure;
  40077. },
  40078. /**
  40079. * The camera exposure used on this material.
  40080. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40081. * This corresponds to a photographic exposure.
  40082. */
  40083. set: function (value) {
  40084. this._imageProcessingConfiguration.exposure = value;
  40085. },
  40086. enumerable: true,
  40087. configurable: true
  40088. });
  40089. ;
  40090. ;
  40091. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  40092. /**
  40093. * Gets The camera contrast used on this material.
  40094. */
  40095. get: function () {
  40096. return this._imageProcessingConfiguration.contrast;
  40097. },
  40098. /**
  40099. * Sets The camera contrast used on this material.
  40100. */
  40101. set: function (value) {
  40102. this._imageProcessingConfiguration.contrast = value;
  40103. },
  40104. enumerable: true,
  40105. configurable: true
  40106. });
  40107. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  40108. /**
  40109. * Gets the Color Grading 2D Lookup Texture.
  40110. */
  40111. get: function () {
  40112. return this._imageProcessingConfiguration.colorGradingTexture;
  40113. },
  40114. /**
  40115. * Sets the Color Grading 2D Lookup Texture.
  40116. */
  40117. set: function (value) {
  40118. this._imageProcessingConfiguration.colorGradingTexture = value;
  40119. },
  40120. enumerable: true,
  40121. configurable: true
  40122. });
  40123. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  40124. /**
  40125. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40126. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40127. * 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;
  40128. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40129. */
  40130. get: function () {
  40131. return this._imageProcessingConfiguration.colorCurves;
  40132. },
  40133. /**
  40134. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40135. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40136. * 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;
  40137. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40138. */
  40139. set: function (value) {
  40140. this._imageProcessingConfiguration.colorCurves = value;
  40141. },
  40142. enumerable: true,
  40143. configurable: true
  40144. });
  40145. PBRMaterial.prototype.getClassName = function () {
  40146. return "PBRMaterial";
  40147. };
  40148. PBRMaterial.prototype.getActiveTextures = function () {
  40149. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40150. if (this._albedoTexture) {
  40151. activeTextures.push(this._albedoTexture);
  40152. }
  40153. if (this._ambientTexture) {
  40154. activeTextures.push(this._ambientTexture);
  40155. }
  40156. if (this._opacityTexture) {
  40157. activeTextures.push(this._opacityTexture);
  40158. }
  40159. if (this._reflectionTexture) {
  40160. activeTextures.push(this._reflectionTexture);
  40161. }
  40162. if (this._emissiveTexture) {
  40163. activeTextures.push(this._emissiveTexture);
  40164. }
  40165. if (this._reflectivityTexture) {
  40166. activeTextures.push(this._reflectivityTexture);
  40167. }
  40168. if (this._metallicTexture) {
  40169. activeTextures.push(this._metallicTexture);
  40170. }
  40171. if (this._microSurfaceTexture) {
  40172. activeTextures.push(this._microSurfaceTexture);
  40173. }
  40174. if (this._bumpTexture) {
  40175. activeTextures.push(this._bumpTexture);
  40176. }
  40177. if (this._lightmapTexture) {
  40178. activeTextures.push(this._lightmapTexture);
  40179. }
  40180. if (this._refractionTexture) {
  40181. activeTextures.push(this._refractionTexture);
  40182. }
  40183. return activeTextures;
  40184. };
  40185. PBRMaterial.prototype.hasTexture = function (texture) {
  40186. if (_super.prototype.hasTexture.call(this, texture)) {
  40187. return true;
  40188. }
  40189. if (this._albedoTexture === texture) {
  40190. return true;
  40191. }
  40192. if (this._ambientTexture === texture) {
  40193. return true;
  40194. }
  40195. if (this._opacityTexture === texture) {
  40196. return true;
  40197. }
  40198. if (this._reflectionTexture === texture) {
  40199. return true;
  40200. }
  40201. if (this._reflectivityTexture === texture) {
  40202. return true;
  40203. }
  40204. if (this._metallicTexture === texture) {
  40205. return true;
  40206. }
  40207. if (this._microSurfaceTexture === texture) {
  40208. return true;
  40209. }
  40210. if (this._bumpTexture === texture) {
  40211. return true;
  40212. }
  40213. if (this._lightmapTexture === texture) {
  40214. return true;
  40215. }
  40216. if (this._refractionTexture === texture) {
  40217. return true;
  40218. }
  40219. return false;
  40220. };
  40221. PBRMaterial.prototype.clone = function (name) {
  40222. var _this = this;
  40223. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40224. clone.id = name;
  40225. clone.name = name;
  40226. return clone;
  40227. };
  40228. PBRMaterial.prototype.serialize = function () {
  40229. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40230. serializationObject.customType = "BABYLON.PBRMaterial";
  40231. return serializationObject;
  40232. };
  40233. // Statics
  40234. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40235. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40236. };
  40237. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40238. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40239. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40240. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40241. __decorate([
  40242. BABYLON.serialize(),
  40243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40244. ], PBRMaterial.prototype, "directIntensity", void 0);
  40245. __decorate([
  40246. BABYLON.serialize(),
  40247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40248. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40249. __decorate([
  40250. BABYLON.serialize(),
  40251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40252. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40253. __decorate([
  40254. BABYLON.serialize(),
  40255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40256. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40257. __decorate([
  40258. BABYLON.serialize(),
  40259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40260. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40261. __decorate([
  40262. BABYLON.serializeAsTexture(),
  40263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40264. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40265. __decorate([
  40266. BABYLON.serializeAsTexture(),
  40267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40268. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40269. __decorate([
  40270. BABYLON.serialize(),
  40271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40272. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40273. __decorate([
  40274. BABYLON.serializeAsTexture(),
  40275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40276. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40277. __decorate([
  40278. BABYLON.serializeAsTexture(),
  40279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40280. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40281. __decorate([
  40282. BABYLON.serializeAsTexture(),
  40283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40284. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40285. __decorate([
  40286. BABYLON.serializeAsTexture(),
  40287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40288. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40289. __decorate([
  40290. BABYLON.serializeAsTexture(),
  40291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40292. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40293. __decorate([
  40294. BABYLON.serialize(),
  40295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40296. ], PBRMaterial.prototype, "metallic", void 0);
  40297. __decorate([
  40298. BABYLON.serialize(),
  40299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40300. ], PBRMaterial.prototype, "roughness", void 0);
  40301. __decorate([
  40302. BABYLON.serializeAsTexture(),
  40303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40304. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40305. __decorate([
  40306. BABYLON.serializeAsTexture(),
  40307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40308. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40309. __decorate([
  40310. BABYLON.serializeAsTexture(),
  40311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40312. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40313. __decorate([
  40314. BABYLON.serializeAsTexture(),
  40315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40316. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40317. __decorate([
  40318. BABYLON.serializeAsColor3("ambient"),
  40319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40320. ], PBRMaterial.prototype, "ambientColor", void 0);
  40321. __decorate([
  40322. BABYLON.serializeAsColor3("albedo"),
  40323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40324. ], PBRMaterial.prototype, "albedoColor", void 0);
  40325. __decorate([
  40326. BABYLON.serializeAsColor3("reflectivity"),
  40327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40328. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40329. __decorate([
  40330. BABYLON.serializeAsColor3("reflection"),
  40331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40332. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40333. __decorate([
  40334. BABYLON.serializeAsColor3("emissive"),
  40335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40336. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40337. __decorate([
  40338. BABYLON.serialize(),
  40339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40340. ], PBRMaterial.prototype, "microSurface", void 0);
  40341. __decorate([
  40342. BABYLON.serialize(),
  40343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40344. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40345. __decorate([
  40346. BABYLON.serialize(),
  40347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40348. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40349. __decorate([
  40350. BABYLON.serialize(),
  40351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40352. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40353. __decorate([
  40354. BABYLON.serialize(),
  40355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40356. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40357. __decorate([
  40358. BABYLON.serialize(),
  40359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40360. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40361. __decorate([
  40362. BABYLON.serialize(),
  40363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40364. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40365. __decorate([
  40366. BABYLON.serialize(),
  40367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40368. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40369. __decorate([
  40370. BABYLON.serialize(),
  40371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40372. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40373. __decorate([
  40374. BABYLON.serialize(),
  40375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40376. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40377. __decorate([
  40378. BABYLON.serialize(),
  40379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40380. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40381. __decorate([
  40382. BABYLON.serialize(),
  40383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40384. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40385. __decorate([
  40386. BABYLON.serialize(),
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40388. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40389. __decorate([
  40390. BABYLON.serialize(),
  40391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40392. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40393. __decorate([
  40394. BABYLON.serialize(),
  40395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40396. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40397. __decorate([
  40398. BABYLON.serialize(),
  40399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40400. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40401. __decorate([
  40402. BABYLON.serialize(),
  40403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40404. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40405. __decorate([
  40406. BABYLON.serialize(),
  40407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40408. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40409. __decorate([
  40410. BABYLON.serialize(),
  40411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40412. ], PBRMaterial.prototype, "useParallax", void 0);
  40413. __decorate([
  40414. BABYLON.serialize(),
  40415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40416. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40417. __decorate([
  40418. BABYLON.serialize(),
  40419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40420. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40421. __decorate([
  40422. BABYLON.serialize(),
  40423. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40424. ], PBRMaterial.prototype, "disableLighting", void 0);
  40425. __decorate([
  40426. BABYLON.serialize(),
  40427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40428. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40429. __decorate([
  40430. BABYLON.serialize(),
  40431. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40432. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40433. __decorate([
  40434. BABYLON.serialize(),
  40435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40436. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40437. __decorate([
  40438. BABYLON.serialize(),
  40439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40440. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40441. __decorate([
  40442. BABYLON.serialize(),
  40443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40444. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40445. __decorate([
  40446. BABYLON.serialize(),
  40447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40448. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40449. __decorate([
  40450. BABYLON.serialize(),
  40451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40452. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40453. __decorate([
  40454. BABYLON.serializeAsTexture(),
  40455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40456. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40457. __decorate([
  40458. BABYLON.serialize(),
  40459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40460. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40461. __decorate([
  40462. BABYLON.serialize(),
  40463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40464. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40465. __decorate([
  40466. BABYLON.serialize(),
  40467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40468. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40469. return PBRMaterial;
  40470. }(BABYLON.PBRBaseMaterial));
  40471. BABYLON.PBRMaterial = PBRMaterial;
  40472. })(BABYLON || (BABYLON = {}));
  40473. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40474. var BABYLON;
  40475. (function (BABYLON) {
  40476. /**
  40477. * The PBR material of BJS following the metal roughness convention.
  40478. *
  40479. * This fits to the PBR convention in the GLTF definition:
  40480. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40481. */
  40482. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40483. __extends(PBRMetallicRoughnessMaterial, _super);
  40484. /**
  40485. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40486. *
  40487. * @param name The material name
  40488. * @param scene The scene the material will be use in.
  40489. */
  40490. function PBRMetallicRoughnessMaterial(name, scene) {
  40491. var _this = _super.call(this, name, scene) || this;
  40492. _this._useRoughnessFromMetallicTextureAlpha = false;
  40493. _this._useRoughnessFromMetallicTextureGreen = true;
  40494. _this._useMetallnessFromMetallicTextureBlue = true;
  40495. _this._forceMetallicWorkflow = true;
  40496. return _this;
  40497. }
  40498. /**
  40499. * Return the currrent class name of the material.
  40500. */
  40501. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40502. return "PBRMetallicRoughnessMaterial";
  40503. };
  40504. /**
  40505. * Return the active textures of the material.
  40506. */
  40507. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40508. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40509. if (this.baseTexture) {
  40510. activeTextures.push(this.baseTexture);
  40511. }
  40512. if (this.metallicRoughnessTexture) {
  40513. activeTextures.push(this.metallicRoughnessTexture);
  40514. }
  40515. return activeTextures;
  40516. };
  40517. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40518. if (_super.prototype.hasTexture.call(this, texture)) {
  40519. return true;
  40520. }
  40521. if (this.baseTexture === texture) {
  40522. return true;
  40523. }
  40524. if (this.metallicRoughnessTexture === texture) {
  40525. return true;
  40526. }
  40527. return false;
  40528. };
  40529. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40530. var _this = this;
  40531. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40532. clone.id = name;
  40533. clone.name = name;
  40534. return clone;
  40535. };
  40536. /**
  40537. * Serialize the material to a parsable JSON object.
  40538. */
  40539. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40540. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40541. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40542. return serializationObject;
  40543. };
  40544. /**
  40545. * Parses a JSON object correponding to the serialize function.
  40546. */
  40547. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40548. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40549. };
  40550. __decorate([
  40551. BABYLON.serializeAsColor3(),
  40552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40553. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40554. __decorate([
  40555. BABYLON.serializeAsTexture(),
  40556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40557. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40558. __decorate([
  40559. BABYLON.serialize(),
  40560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40561. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40562. __decorate([
  40563. BABYLON.serialize(),
  40564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40565. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40566. __decorate([
  40567. BABYLON.serializeAsTexture(),
  40568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40569. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40570. return PBRMetallicRoughnessMaterial;
  40571. }(BABYLON.PBRBaseSimpleMaterial));
  40572. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40573. })(BABYLON || (BABYLON = {}));
  40574. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40575. var BABYLON;
  40576. (function (BABYLON) {
  40577. /**
  40578. * The PBR material of BJS following the specular glossiness convention.
  40579. *
  40580. * This fits to the PBR convention in the GLTF definition:
  40581. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40582. */
  40583. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40584. __extends(PBRSpecularGlossinessMaterial, _super);
  40585. /**
  40586. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40587. *
  40588. * @param name The material name
  40589. * @param scene The scene the material will be use in.
  40590. */
  40591. function PBRSpecularGlossinessMaterial(name, scene) {
  40592. var _this = _super.call(this, name, scene) || this;
  40593. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40594. return _this;
  40595. }
  40596. /**
  40597. * Return the currrent class name of the material.
  40598. */
  40599. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40600. return "PBRSpecularGlossinessMaterial";
  40601. };
  40602. /**
  40603. * Return the active textures of the material.
  40604. */
  40605. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40606. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40607. if (this.diffuseTexture) {
  40608. activeTextures.push(this.diffuseTexture);
  40609. }
  40610. if (this.specularGlossinessTexture) {
  40611. activeTextures.push(this.specularGlossinessTexture);
  40612. }
  40613. return activeTextures;
  40614. };
  40615. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40616. if (_super.prototype.hasTexture.call(this, texture)) {
  40617. return true;
  40618. }
  40619. if (this.diffuseTexture === texture) {
  40620. return true;
  40621. }
  40622. if (this.specularGlossinessTexture === texture) {
  40623. return true;
  40624. }
  40625. return false;
  40626. };
  40627. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40628. var _this = this;
  40629. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40630. clone.id = name;
  40631. clone.name = name;
  40632. return clone;
  40633. };
  40634. /**
  40635. * Serialize the material to a parsable JSON object.
  40636. */
  40637. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40638. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40639. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40640. return serializationObject;
  40641. };
  40642. /**
  40643. * Parses a JSON object correponding to the serialize function.
  40644. */
  40645. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40646. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40647. };
  40648. __decorate([
  40649. BABYLON.serializeAsColor3("diffuse"),
  40650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40651. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40652. __decorate([
  40653. BABYLON.serializeAsTexture(),
  40654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40655. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40656. __decorate([
  40657. BABYLON.serializeAsColor3("specular"),
  40658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40659. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40660. __decorate([
  40661. BABYLON.serialize(),
  40662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40663. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40664. __decorate([
  40665. BABYLON.serializeAsTexture(),
  40666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40667. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40668. return PBRSpecularGlossinessMaterial;
  40669. }(BABYLON.PBRBaseSimpleMaterial));
  40670. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40671. })(BABYLON || (BABYLON = {}));
  40672. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40673. var BABYLON;
  40674. (function (BABYLON) {
  40675. BABYLON.CameraInputTypes = {};
  40676. var CameraInputsManager = /** @class */ (function () {
  40677. function CameraInputsManager(camera) {
  40678. this.attached = {};
  40679. this.camera = camera;
  40680. this.checkInputs = function () { };
  40681. }
  40682. /**
  40683. * Add an input method to a camera.
  40684. * builtin inputs example: camera.inputs.addGamepad();
  40685. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40686. * @param input camera input method
  40687. */
  40688. CameraInputsManager.prototype.add = function (input) {
  40689. var type = input.getSimpleName();
  40690. if (this.attached[type]) {
  40691. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40692. return;
  40693. }
  40694. this.attached[type] = input;
  40695. input.camera = this.camera;
  40696. //for checkInputs, we are dynamically creating a function
  40697. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40698. if (input.checkInputs) {
  40699. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40700. }
  40701. if (this.attachedElement) {
  40702. input.attachControl(this.attachedElement);
  40703. }
  40704. };
  40705. /**
  40706. * Remove a specific input method from a camera
  40707. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40708. * @param inputToRemove camera input method
  40709. */
  40710. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40711. for (var cam in this.attached) {
  40712. var input = this.attached[cam];
  40713. if (input === inputToRemove) {
  40714. input.detachControl(this.attachedElement);
  40715. input.camera = null;
  40716. delete this.attached[cam];
  40717. this.rebuildInputCheck();
  40718. }
  40719. }
  40720. };
  40721. CameraInputsManager.prototype.removeByType = function (inputType) {
  40722. for (var cam in this.attached) {
  40723. var input = this.attached[cam];
  40724. if (input.getClassName() === inputType) {
  40725. input.detachControl(this.attachedElement);
  40726. input.camera = null;
  40727. delete this.attached[cam];
  40728. this.rebuildInputCheck();
  40729. }
  40730. }
  40731. };
  40732. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40733. var current = this.checkInputs;
  40734. return function () {
  40735. current();
  40736. fn();
  40737. };
  40738. };
  40739. CameraInputsManager.prototype.attachInput = function (input) {
  40740. if (this.attachedElement) {
  40741. input.attachControl(this.attachedElement, this.noPreventDefault);
  40742. }
  40743. };
  40744. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40745. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40746. if (this.attachedElement) {
  40747. return;
  40748. }
  40749. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40750. this.attachedElement = element;
  40751. this.noPreventDefault = noPreventDefault;
  40752. for (var cam in this.attached) {
  40753. this.attached[cam].attachControl(element, noPreventDefault);
  40754. }
  40755. };
  40756. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40757. if (disconnect === void 0) { disconnect = false; }
  40758. if (this.attachedElement !== element) {
  40759. return;
  40760. }
  40761. for (var cam in this.attached) {
  40762. this.attached[cam].detachControl(element);
  40763. if (disconnect) {
  40764. this.attached[cam].camera = null;
  40765. }
  40766. }
  40767. this.attachedElement = null;
  40768. };
  40769. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40770. this.checkInputs = function () { };
  40771. for (var cam in this.attached) {
  40772. var input = this.attached[cam];
  40773. if (input.checkInputs) {
  40774. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40775. }
  40776. }
  40777. };
  40778. /**
  40779. * Remove all attached input methods from a camera
  40780. */
  40781. CameraInputsManager.prototype.clear = function () {
  40782. if (this.attachedElement) {
  40783. this.detachElement(this.attachedElement, true);
  40784. }
  40785. this.attached = {};
  40786. this.attachedElement = null;
  40787. this.checkInputs = function () { };
  40788. };
  40789. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40790. var inputs = {};
  40791. for (var cam in this.attached) {
  40792. var input = this.attached[cam];
  40793. var res = BABYLON.SerializationHelper.Serialize(input);
  40794. inputs[input.getClassName()] = res;
  40795. }
  40796. serializedCamera.inputsmgr = inputs;
  40797. };
  40798. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40799. var parsedInputs = parsedCamera.inputsmgr;
  40800. if (parsedInputs) {
  40801. this.clear();
  40802. for (var n in parsedInputs) {
  40803. var construct = BABYLON.CameraInputTypes[n];
  40804. if (construct) {
  40805. var parsedinput = parsedInputs[n];
  40806. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40807. this.add(input);
  40808. }
  40809. }
  40810. }
  40811. else {
  40812. //2016-03-08 this part is for managing backward compatibility
  40813. for (var n in this.attached) {
  40814. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40815. if (construct) {
  40816. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40817. this.remove(this.attached[n]);
  40818. this.add(input);
  40819. }
  40820. }
  40821. }
  40822. };
  40823. return CameraInputsManager;
  40824. }());
  40825. BABYLON.CameraInputsManager = CameraInputsManager;
  40826. })(BABYLON || (BABYLON = {}));
  40827. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40828. var BABYLON;
  40829. (function (BABYLON) {
  40830. var TargetCamera = /** @class */ (function (_super) {
  40831. __extends(TargetCamera, _super);
  40832. function TargetCamera(name, position, scene) {
  40833. var _this = _super.call(this, name, position, scene) || this;
  40834. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40835. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40836. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40837. _this.speed = 2.0;
  40838. _this.noRotationConstraint = false;
  40839. _this.lockedTarget = null;
  40840. _this._currentTarget = BABYLON.Vector3.Zero();
  40841. _this._viewMatrix = BABYLON.Matrix.Zero();
  40842. _this._camMatrix = BABYLON.Matrix.Zero();
  40843. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40844. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40845. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40846. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40847. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40848. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40849. _this._tempMatrix = BABYLON.Matrix.Zero();
  40850. return _this;
  40851. }
  40852. TargetCamera.prototype.getFrontPosition = function (distance) {
  40853. this.getWorldMatrix();
  40854. var direction = this.getTarget().subtract(this.position);
  40855. direction.normalize();
  40856. direction.scaleInPlace(distance);
  40857. return this.globalPosition.add(direction);
  40858. };
  40859. TargetCamera.prototype._getLockedTargetPosition = function () {
  40860. if (!this.lockedTarget) {
  40861. return null;
  40862. }
  40863. if (this.lockedTarget.absolutePosition) {
  40864. this.lockedTarget.computeWorldMatrix();
  40865. }
  40866. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40867. };
  40868. TargetCamera.prototype.storeState = function () {
  40869. this._storedPosition = this.position.clone();
  40870. this._storedRotation = this.rotation.clone();
  40871. if (this.rotationQuaternion) {
  40872. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40873. }
  40874. return _super.prototype.storeState.call(this);
  40875. };
  40876. /**
  40877. * Restored camera state. You must call storeState() first
  40878. */
  40879. TargetCamera.prototype._restoreStateValues = function () {
  40880. if (!_super.prototype._restoreStateValues.call(this)) {
  40881. return false;
  40882. }
  40883. this.position = this._storedPosition.clone();
  40884. this.rotation = this._storedRotation.clone();
  40885. if (this.rotationQuaternion) {
  40886. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40887. }
  40888. this.cameraDirection.copyFromFloats(0, 0, 0);
  40889. this.cameraRotation.copyFromFloats(0, 0);
  40890. return true;
  40891. };
  40892. // Cache
  40893. TargetCamera.prototype._initCache = function () {
  40894. _super.prototype._initCache.call(this);
  40895. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40896. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40897. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40898. };
  40899. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40900. if (!ignoreParentClass) {
  40901. _super.prototype._updateCache.call(this);
  40902. }
  40903. var lockedTargetPosition = this._getLockedTargetPosition();
  40904. if (!lockedTargetPosition) {
  40905. this._cache.lockedTarget = null;
  40906. }
  40907. else {
  40908. if (!this._cache.lockedTarget) {
  40909. this._cache.lockedTarget = lockedTargetPosition.clone();
  40910. }
  40911. else {
  40912. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40913. }
  40914. }
  40915. this._cache.rotation.copyFrom(this.rotation);
  40916. if (this.rotationQuaternion)
  40917. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40918. };
  40919. // Synchronized
  40920. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40921. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40922. return false;
  40923. }
  40924. var lockedTargetPosition = this._getLockedTargetPosition();
  40925. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40926. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40927. };
  40928. // Methods
  40929. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40930. var engine = this.getEngine();
  40931. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40932. };
  40933. // Target
  40934. TargetCamera.prototype.setTarget = function (target) {
  40935. this.upVector.normalize();
  40936. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40937. this._camMatrix.invert();
  40938. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40939. var vDir = target.subtract(this.position);
  40940. if (vDir.x >= 0.0) {
  40941. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40942. }
  40943. else {
  40944. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40945. }
  40946. this.rotation.z = 0;
  40947. if (isNaN(this.rotation.x)) {
  40948. this.rotation.x = 0;
  40949. }
  40950. if (isNaN(this.rotation.y)) {
  40951. this.rotation.y = 0;
  40952. }
  40953. if (isNaN(this.rotation.z)) {
  40954. this.rotation.z = 0;
  40955. }
  40956. if (this.rotationQuaternion) {
  40957. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40958. }
  40959. };
  40960. /**
  40961. * Return the current target position of the camera. This value is expressed in local space.
  40962. */
  40963. TargetCamera.prototype.getTarget = function () {
  40964. return this._currentTarget;
  40965. };
  40966. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40967. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40968. };
  40969. TargetCamera.prototype._updatePosition = function () {
  40970. if (this.parent) {
  40971. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40972. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40973. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40974. return;
  40975. }
  40976. this.position.addInPlace(this.cameraDirection);
  40977. };
  40978. TargetCamera.prototype._checkInputs = function () {
  40979. var needToMove = this._decideIfNeedsToMove();
  40980. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40981. // Move
  40982. if (needToMove) {
  40983. this._updatePosition();
  40984. }
  40985. // Rotate
  40986. if (needToRotate) {
  40987. this.rotation.x += this.cameraRotation.x;
  40988. this.rotation.y += this.cameraRotation.y;
  40989. //rotate, if quaternion is set and rotation was used
  40990. if (this.rotationQuaternion) {
  40991. var len = this.rotation.lengthSquared();
  40992. if (len) {
  40993. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40994. }
  40995. }
  40996. if (!this.noRotationConstraint) {
  40997. var limit = (Math.PI / 2) * 0.95;
  40998. if (this.rotation.x > limit)
  40999. this.rotation.x = limit;
  41000. if (this.rotation.x < -limit)
  41001. this.rotation.x = -limit;
  41002. }
  41003. }
  41004. // Inertia
  41005. if (needToMove) {
  41006. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  41007. this.cameraDirection.x = 0;
  41008. }
  41009. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  41010. this.cameraDirection.y = 0;
  41011. }
  41012. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  41013. this.cameraDirection.z = 0;
  41014. }
  41015. this.cameraDirection.scaleInPlace(this.inertia);
  41016. }
  41017. if (needToRotate) {
  41018. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  41019. this.cameraRotation.x = 0;
  41020. }
  41021. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  41022. this.cameraRotation.y = 0;
  41023. }
  41024. this.cameraRotation.scaleInPlace(this.inertia);
  41025. }
  41026. _super.prototype._checkInputs.call(this);
  41027. };
  41028. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  41029. if (this.rotationQuaternion) {
  41030. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  41031. }
  41032. else {
  41033. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  41034. }
  41035. //update the up vector!
  41036. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  41037. };
  41038. TargetCamera.prototype._getViewMatrix = function () {
  41039. if (this.lockedTarget) {
  41040. this.setTarget(this._getLockedTargetPosition());
  41041. }
  41042. // Compute
  41043. this._updateCameraRotationMatrix();
  41044. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  41045. // Computing target and final matrix
  41046. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  41047. if (this.getScene().useRightHandedSystem) {
  41048. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  41049. }
  41050. else {
  41051. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  41052. }
  41053. return this._viewMatrix;
  41054. };
  41055. /**
  41056. * @override
  41057. * Override Camera.createRigCamera
  41058. */
  41059. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  41060. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  41061. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  41062. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  41063. if (!this.rotationQuaternion) {
  41064. this.rotationQuaternion = new BABYLON.Quaternion();
  41065. }
  41066. rigCamera._cameraRigParams = {};
  41067. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  41068. }
  41069. return rigCamera;
  41070. }
  41071. return null;
  41072. };
  41073. /**
  41074. * @override
  41075. * Override Camera._updateRigCameras
  41076. */
  41077. TargetCamera.prototype._updateRigCameras = function () {
  41078. var camLeft = this._rigCameras[0];
  41079. var camRight = this._rigCameras[1];
  41080. switch (this.cameraRigMode) {
  41081. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41082. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41084. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41085. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  41086. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  41087. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  41088. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  41089. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  41090. camLeft.setTarget(this.getTarget());
  41091. camRight.setTarget(this.getTarget());
  41092. break;
  41093. case BABYLON.Camera.RIG_MODE_VR:
  41094. if (camLeft.rotationQuaternion) {
  41095. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  41096. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  41097. }
  41098. else {
  41099. camLeft.rotation.copyFrom(this.rotation);
  41100. camRight.rotation.copyFrom(this.rotation);
  41101. }
  41102. camLeft.position.copyFrom(this.position);
  41103. camRight.position.copyFrom(this.position);
  41104. break;
  41105. }
  41106. _super.prototype._updateRigCameras.call(this);
  41107. };
  41108. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  41109. if (!this._rigCamTransformMatrix) {
  41110. this._rigCamTransformMatrix = new BABYLON.Matrix();
  41111. }
  41112. var target = this.getTarget();
  41113. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  41114. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  41115. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  41116. };
  41117. TargetCamera.prototype.getClassName = function () {
  41118. return "TargetCamera";
  41119. };
  41120. __decorate([
  41121. BABYLON.serializeAsVector3()
  41122. ], TargetCamera.prototype, "rotation", void 0);
  41123. __decorate([
  41124. BABYLON.serialize()
  41125. ], TargetCamera.prototype, "speed", void 0);
  41126. __decorate([
  41127. BABYLON.serializeAsMeshReference("lockedTargetId")
  41128. ], TargetCamera.prototype, "lockedTarget", void 0);
  41129. return TargetCamera;
  41130. }(BABYLON.Camera));
  41131. BABYLON.TargetCamera = TargetCamera;
  41132. })(BABYLON || (BABYLON = {}));
  41133. //# sourceMappingURL=babylon.targetCamera.js.map
  41134. var BABYLON;
  41135. (function (BABYLON) {
  41136. var FreeCameraMouseInput = /** @class */ (function () {
  41137. function FreeCameraMouseInput(touchEnabled) {
  41138. if (touchEnabled === void 0) { touchEnabled = true; }
  41139. this.touchEnabled = touchEnabled;
  41140. this.buttons = [0, 1, 2];
  41141. this.angularSensibility = 2000.0;
  41142. this.previousPosition = null;
  41143. }
  41144. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  41145. var _this = this;
  41146. var engine = this.camera.getEngine();
  41147. if (!this._pointerInput) {
  41148. this._pointerInput = function (p, s) {
  41149. var evt = p.event;
  41150. if (engine.isInVRExclusivePointerMode) {
  41151. return;
  41152. }
  41153. if (!_this.touchEnabled && evt.pointerType === "touch") {
  41154. return;
  41155. }
  41156. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41157. return;
  41158. }
  41159. var srcElement = (evt.srcElement || evt.target);
  41160. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41161. try {
  41162. srcElement.setPointerCapture(evt.pointerId);
  41163. }
  41164. catch (e) {
  41165. //Nothing to do with the error. Execution will continue.
  41166. }
  41167. _this.previousPosition = {
  41168. x: evt.clientX,
  41169. y: evt.clientY
  41170. };
  41171. if (!noPreventDefault) {
  41172. evt.preventDefault();
  41173. element.focus();
  41174. }
  41175. }
  41176. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41177. try {
  41178. srcElement.releasePointerCapture(evt.pointerId);
  41179. }
  41180. catch (e) {
  41181. //Nothing to do with the error.
  41182. }
  41183. _this.previousPosition = null;
  41184. if (!noPreventDefault) {
  41185. evt.preventDefault();
  41186. }
  41187. }
  41188. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41189. if (!_this.previousPosition || engine.isPointerLock) {
  41190. return;
  41191. }
  41192. var offsetX = evt.clientX - _this.previousPosition.x;
  41193. var offsetY = evt.clientY - _this.previousPosition.y;
  41194. if (_this.camera.getScene().useRightHandedSystem) {
  41195. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41196. }
  41197. else {
  41198. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41199. }
  41200. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41201. _this.previousPosition = {
  41202. x: evt.clientX,
  41203. y: evt.clientY
  41204. };
  41205. if (!noPreventDefault) {
  41206. evt.preventDefault();
  41207. }
  41208. }
  41209. };
  41210. }
  41211. this._onMouseMove = function (evt) {
  41212. if (!engine.isPointerLock) {
  41213. return;
  41214. }
  41215. if (engine.isInVRExclusivePointerMode) {
  41216. return;
  41217. }
  41218. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41219. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41220. if (_this.camera.getScene().useRightHandedSystem) {
  41221. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41222. }
  41223. else {
  41224. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41225. }
  41226. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41227. _this.previousPosition = null;
  41228. if (!noPreventDefault) {
  41229. evt.preventDefault();
  41230. }
  41231. };
  41232. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41233. element.addEventListener("mousemove", this._onMouseMove, false);
  41234. };
  41235. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41236. if (this._observer && element) {
  41237. this.camera.getScene().onPointerObservable.remove(this._observer);
  41238. if (this._onMouseMove) {
  41239. element.removeEventListener("mousemove", this._onMouseMove);
  41240. }
  41241. this._observer = null;
  41242. this._onMouseMove = null;
  41243. this.previousPosition = null;
  41244. }
  41245. };
  41246. FreeCameraMouseInput.prototype.getClassName = function () {
  41247. return "FreeCameraMouseInput";
  41248. };
  41249. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41250. return "mouse";
  41251. };
  41252. __decorate([
  41253. BABYLON.serialize()
  41254. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41255. __decorate([
  41256. BABYLON.serialize()
  41257. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41258. return FreeCameraMouseInput;
  41259. }());
  41260. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41261. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41262. })(BABYLON || (BABYLON = {}));
  41263. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41264. var BABYLON;
  41265. (function (BABYLON) {
  41266. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41267. function FreeCameraKeyboardMoveInput() {
  41268. this._keys = new Array();
  41269. this.keysUp = [38];
  41270. this.keysDown = [40];
  41271. this.keysLeft = [37];
  41272. this.keysRight = [39];
  41273. }
  41274. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41275. var _this = this;
  41276. if (this._onCanvasBlurObserver) {
  41277. return;
  41278. }
  41279. this._scene = this.camera.getScene();
  41280. this._engine = this._scene.getEngine();
  41281. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41282. _this._keys = [];
  41283. });
  41284. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41285. var evt = info.event;
  41286. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41287. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41288. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41289. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41290. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41291. var index = _this._keys.indexOf(evt.keyCode);
  41292. if (index === -1) {
  41293. _this._keys.push(evt.keyCode);
  41294. }
  41295. if (!noPreventDefault) {
  41296. evt.preventDefault();
  41297. }
  41298. }
  41299. }
  41300. else {
  41301. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41302. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41303. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41304. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41305. var index = _this._keys.indexOf(evt.keyCode);
  41306. if (index >= 0) {
  41307. _this._keys.splice(index, 1);
  41308. }
  41309. if (!noPreventDefault) {
  41310. evt.preventDefault();
  41311. }
  41312. }
  41313. }
  41314. });
  41315. };
  41316. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41317. if (this._scene) {
  41318. if (this._onKeyboardObserver) {
  41319. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41320. }
  41321. if (this._onCanvasBlurObserver) {
  41322. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41323. }
  41324. this._onKeyboardObserver = null;
  41325. this._onCanvasBlurObserver = null;
  41326. }
  41327. this._keys = [];
  41328. };
  41329. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41330. if (this._onKeyboardObserver) {
  41331. var camera = this.camera;
  41332. // Keyboard
  41333. for (var index = 0; index < this._keys.length; index++) {
  41334. var keyCode = this._keys[index];
  41335. var speed = camera._computeLocalCameraSpeed();
  41336. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41337. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41338. }
  41339. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41340. camera._localDirection.copyFromFloats(0, 0, speed);
  41341. }
  41342. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41343. camera._localDirection.copyFromFloats(speed, 0, 0);
  41344. }
  41345. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41346. camera._localDirection.copyFromFloats(0, 0, -speed);
  41347. }
  41348. if (camera.getScene().useRightHandedSystem) {
  41349. camera._localDirection.z *= -1;
  41350. }
  41351. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41352. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41353. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41354. }
  41355. }
  41356. };
  41357. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41358. return "FreeCameraKeyboardMoveInput";
  41359. };
  41360. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41361. this._keys = [];
  41362. };
  41363. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41364. return "keyboard";
  41365. };
  41366. __decorate([
  41367. BABYLON.serialize()
  41368. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41369. __decorate([
  41370. BABYLON.serialize()
  41371. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41372. __decorate([
  41373. BABYLON.serialize()
  41374. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41375. __decorate([
  41376. BABYLON.serialize()
  41377. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41378. return FreeCameraKeyboardMoveInput;
  41379. }());
  41380. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41381. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41382. })(BABYLON || (BABYLON = {}));
  41383. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41384. var BABYLON;
  41385. (function (BABYLON) {
  41386. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41387. __extends(FreeCameraInputsManager, _super);
  41388. function FreeCameraInputsManager(camera) {
  41389. return _super.call(this, camera) || this;
  41390. }
  41391. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41392. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41393. return this;
  41394. };
  41395. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41396. if (touchEnabled === void 0) { touchEnabled = true; }
  41397. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41398. return this;
  41399. };
  41400. FreeCameraInputsManager.prototype.addGamepad = function () {
  41401. this.add(new BABYLON.FreeCameraGamepadInput());
  41402. return this;
  41403. };
  41404. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41405. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41406. return this;
  41407. };
  41408. FreeCameraInputsManager.prototype.addTouch = function () {
  41409. this.add(new BABYLON.FreeCameraTouchInput());
  41410. return this;
  41411. };
  41412. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41413. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41414. return this;
  41415. };
  41416. return FreeCameraInputsManager;
  41417. }(BABYLON.CameraInputsManager));
  41418. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41419. })(BABYLON || (BABYLON = {}));
  41420. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41421. var BABYLON;
  41422. (function (BABYLON) {
  41423. var FreeCamera = /** @class */ (function (_super) {
  41424. __extends(FreeCamera, _super);
  41425. function FreeCamera(name, position, scene) {
  41426. var _this = _super.call(this, name, position, scene) || this;
  41427. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41428. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41429. _this.checkCollisions = false;
  41430. _this.applyGravity = false;
  41431. _this._needMoveForGravity = false;
  41432. _this._oldPosition = BABYLON.Vector3.Zero();
  41433. _this._diffPosition = BABYLON.Vector3.Zero();
  41434. _this._newPosition = BABYLON.Vector3.Zero();
  41435. // Collisions
  41436. _this._collisionMask = -1;
  41437. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41438. if (collidedMesh === void 0) { collidedMesh = null; }
  41439. //TODO move this to the collision coordinator!
  41440. if (_this.getScene().workerCollisions)
  41441. newPosition.multiplyInPlace(_this._collider._radius);
  41442. var updatePosition = function (newPos) {
  41443. _this._newPosition.copyFrom(newPos);
  41444. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41445. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41446. _this.position.addInPlace(_this._diffPosition);
  41447. if (_this.onCollide && collidedMesh) {
  41448. _this.onCollide(collidedMesh);
  41449. }
  41450. }
  41451. };
  41452. updatePosition(newPosition);
  41453. };
  41454. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41455. _this.inputs.addKeyboard().addMouse();
  41456. return _this;
  41457. }
  41458. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41459. //-- begin properties for backward compatibility for inputs
  41460. /**
  41461. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41462. * Higher values reduce sensitivity.
  41463. */
  41464. get: function () {
  41465. var mouse = this.inputs.attached["mouse"];
  41466. if (mouse)
  41467. return mouse.angularSensibility;
  41468. return 0;
  41469. },
  41470. /**
  41471. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41472. * Higher values reduce sensitivity.
  41473. */
  41474. set: function (value) {
  41475. var mouse = this.inputs.attached["mouse"];
  41476. if (mouse)
  41477. mouse.angularSensibility = value;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41483. get: function () {
  41484. var keyboard = this.inputs.attached["keyboard"];
  41485. if (keyboard)
  41486. return keyboard.keysUp;
  41487. return [];
  41488. },
  41489. set: function (value) {
  41490. var keyboard = this.inputs.attached["keyboard"];
  41491. if (keyboard)
  41492. keyboard.keysUp = value;
  41493. },
  41494. enumerable: true,
  41495. configurable: true
  41496. });
  41497. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41498. get: function () {
  41499. var keyboard = this.inputs.attached["keyboard"];
  41500. if (keyboard)
  41501. return keyboard.keysDown;
  41502. return [];
  41503. },
  41504. set: function (value) {
  41505. var keyboard = this.inputs.attached["keyboard"];
  41506. if (keyboard)
  41507. keyboard.keysDown = value;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41513. get: function () {
  41514. var keyboard = this.inputs.attached["keyboard"];
  41515. if (keyboard)
  41516. return keyboard.keysLeft;
  41517. return [];
  41518. },
  41519. set: function (value) {
  41520. var keyboard = this.inputs.attached["keyboard"];
  41521. if (keyboard)
  41522. keyboard.keysLeft = value;
  41523. },
  41524. enumerable: true,
  41525. configurable: true
  41526. });
  41527. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41528. get: function () {
  41529. var keyboard = this.inputs.attached["keyboard"];
  41530. if (keyboard)
  41531. return keyboard.keysRight;
  41532. return [];
  41533. },
  41534. set: function (value) {
  41535. var keyboard = this.inputs.attached["keyboard"];
  41536. if (keyboard)
  41537. keyboard.keysRight = value;
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. // Controls
  41543. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41544. this.inputs.attachElement(element, noPreventDefault);
  41545. };
  41546. FreeCamera.prototype.detachControl = function (element) {
  41547. this.inputs.detachElement(element);
  41548. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41549. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41550. };
  41551. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41552. get: function () {
  41553. return this._collisionMask;
  41554. },
  41555. set: function (mask) {
  41556. this._collisionMask = !isNaN(mask) ? mask : -1;
  41557. },
  41558. enumerable: true,
  41559. configurable: true
  41560. });
  41561. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41562. var globalPosition;
  41563. if (this.parent) {
  41564. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41565. }
  41566. else {
  41567. globalPosition = this.position;
  41568. }
  41569. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41570. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41571. if (!this._collider) {
  41572. this._collider = new BABYLON.Collider();
  41573. }
  41574. this._collider._radius = this.ellipsoid;
  41575. this._collider.collisionMask = this._collisionMask;
  41576. //no need for clone, as long as gravity is not on.
  41577. var actualDisplacement = displacement;
  41578. //add gravity to the direction to prevent the dual-collision checking
  41579. if (this.applyGravity) {
  41580. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41581. actualDisplacement = displacement.add(this.getScene().gravity);
  41582. }
  41583. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41584. };
  41585. FreeCamera.prototype._checkInputs = function () {
  41586. if (!this._localDirection) {
  41587. this._localDirection = BABYLON.Vector3.Zero();
  41588. this._transformedDirection = BABYLON.Vector3.Zero();
  41589. }
  41590. this.inputs.checkInputs();
  41591. _super.prototype._checkInputs.call(this);
  41592. };
  41593. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41594. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41595. };
  41596. FreeCamera.prototype._updatePosition = function () {
  41597. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41598. this._collideWithWorld(this.cameraDirection);
  41599. }
  41600. else {
  41601. _super.prototype._updatePosition.call(this);
  41602. }
  41603. };
  41604. FreeCamera.prototype.dispose = function () {
  41605. this.inputs.clear();
  41606. _super.prototype.dispose.call(this);
  41607. };
  41608. FreeCamera.prototype.getClassName = function () {
  41609. return "FreeCamera";
  41610. };
  41611. __decorate([
  41612. BABYLON.serializeAsVector3()
  41613. ], FreeCamera.prototype, "ellipsoid", void 0);
  41614. __decorate([
  41615. BABYLON.serializeAsVector3()
  41616. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41617. __decorate([
  41618. BABYLON.serialize()
  41619. ], FreeCamera.prototype, "checkCollisions", void 0);
  41620. __decorate([
  41621. BABYLON.serialize()
  41622. ], FreeCamera.prototype, "applyGravity", void 0);
  41623. return FreeCamera;
  41624. }(BABYLON.TargetCamera));
  41625. BABYLON.FreeCamera = FreeCamera;
  41626. })(BABYLON || (BABYLON = {}));
  41627. //# sourceMappingURL=babylon.freeCamera.js.map
  41628. var BABYLON;
  41629. (function (BABYLON) {
  41630. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41631. function ArcRotateCameraKeyboardMoveInput() {
  41632. this._keys = new Array();
  41633. this.keysUp = [38];
  41634. this.keysDown = [40];
  41635. this.keysLeft = [37];
  41636. this.keysRight = [39];
  41637. this.keysReset = [220];
  41638. this.panningSensibility = 50.0;
  41639. this.zoomingSensibility = 25.0;
  41640. this.useAltToZoom = true;
  41641. }
  41642. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41643. var _this = this;
  41644. if (this._onCanvasBlurObserver) {
  41645. return;
  41646. }
  41647. this._scene = this.camera.getScene();
  41648. this._engine = this._scene.getEngine();
  41649. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41650. _this._keys = [];
  41651. });
  41652. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41653. var evt = info.event;
  41654. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41655. _this._ctrlPressed = evt.ctrlKey;
  41656. _this._altPressed = evt.altKey;
  41657. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41658. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41659. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41660. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41661. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41662. var index = _this._keys.indexOf(evt.keyCode);
  41663. if (index === -1) {
  41664. _this._keys.push(evt.keyCode);
  41665. }
  41666. if (evt.preventDefault) {
  41667. if (!noPreventDefault) {
  41668. evt.preventDefault();
  41669. }
  41670. }
  41671. }
  41672. }
  41673. else {
  41674. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41675. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41676. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41677. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41678. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41679. var index = _this._keys.indexOf(evt.keyCode);
  41680. if (index >= 0) {
  41681. _this._keys.splice(index, 1);
  41682. }
  41683. if (evt.preventDefault) {
  41684. if (!noPreventDefault) {
  41685. evt.preventDefault();
  41686. }
  41687. }
  41688. }
  41689. }
  41690. });
  41691. };
  41692. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41693. if (this._scene) {
  41694. if (this._onKeyboardObserver) {
  41695. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41696. }
  41697. if (this._onCanvasBlurObserver) {
  41698. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41699. }
  41700. this._onKeyboardObserver = null;
  41701. this._onCanvasBlurObserver = null;
  41702. }
  41703. this._keys = [];
  41704. };
  41705. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41706. if (this._onKeyboardObserver) {
  41707. var camera = this.camera;
  41708. for (var index = 0; index < this._keys.length; index++) {
  41709. var keyCode = this._keys[index];
  41710. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41711. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41712. camera.inertialPanningX -= 1 / this.panningSensibility;
  41713. }
  41714. else {
  41715. camera.inertialAlphaOffset -= 0.01;
  41716. }
  41717. }
  41718. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41719. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41720. camera.inertialPanningY += 1 / this.panningSensibility;
  41721. }
  41722. else if (this._altPressed && this.useAltToZoom) {
  41723. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41724. }
  41725. else {
  41726. camera.inertialBetaOffset -= 0.01;
  41727. }
  41728. }
  41729. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41730. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41731. camera.inertialPanningX += 1 / this.panningSensibility;
  41732. }
  41733. else {
  41734. camera.inertialAlphaOffset += 0.01;
  41735. }
  41736. }
  41737. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41738. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41739. camera.inertialPanningY -= 1 / this.panningSensibility;
  41740. }
  41741. else if (this._altPressed && this.useAltToZoom) {
  41742. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41743. }
  41744. else {
  41745. camera.inertialBetaOffset += 0.01;
  41746. }
  41747. }
  41748. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41749. camera.restoreState();
  41750. }
  41751. }
  41752. }
  41753. };
  41754. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41755. return "ArcRotateCameraKeyboardMoveInput";
  41756. };
  41757. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41758. return "keyboard";
  41759. };
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41766. __decorate([
  41767. BABYLON.serialize()
  41768. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41769. __decorate([
  41770. BABYLON.serialize()
  41771. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41772. __decorate([
  41773. BABYLON.serialize()
  41774. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41775. __decorate([
  41776. BABYLON.serialize()
  41777. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41778. __decorate([
  41779. BABYLON.serialize()
  41780. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41781. __decorate([
  41782. BABYLON.serialize()
  41783. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41784. return ArcRotateCameraKeyboardMoveInput;
  41785. }());
  41786. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41787. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41788. })(BABYLON || (BABYLON = {}));
  41789. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41790. var BABYLON;
  41791. (function (BABYLON) {
  41792. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41793. function ArcRotateCameraMouseWheelInput() {
  41794. this.wheelPrecision = 3.0;
  41795. /**
  41796. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41797. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41798. */
  41799. this.wheelDeltaPercentage = 0;
  41800. }
  41801. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41802. var _this = this;
  41803. this._wheel = function (p, s) {
  41804. //sanity check - this should be a PointerWheel event.
  41805. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41806. return;
  41807. var event = p.event;
  41808. var delta = 0;
  41809. if (event.wheelDelta) {
  41810. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41811. }
  41812. else if (event.detail) {
  41813. delta = -event.detail / _this.wheelPrecision;
  41814. }
  41815. if (delta)
  41816. _this.camera.inertialRadiusOffset += delta;
  41817. if (event.preventDefault) {
  41818. if (!noPreventDefault) {
  41819. event.preventDefault();
  41820. }
  41821. }
  41822. };
  41823. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41824. };
  41825. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41826. if (this._observer && element) {
  41827. this.camera.getScene().onPointerObservable.remove(this._observer);
  41828. this._observer = null;
  41829. this._wheel = null;
  41830. }
  41831. };
  41832. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41833. return "ArcRotateCameraMouseWheelInput";
  41834. };
  41835. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41836. return "mousewheel";
  41837. };
  41838. __decorate([
  41839. BABYLON.serialize()
  41840. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41841. __decorate([
  41842. BABYLON.serialize()
  41843. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41844. return ArcRotateCameraMouseWheelInput;
  41845. }());
  41846. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41847. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41848. })(BABYLON || (BABYLON = {}));
  41849. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41850. var BABYLON;
  41851. (function (BABYLON) {
  41852. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41853. function ArcRotateCameraPointersInput() {
  41854. this.buttons = [0, 1, 2];
  41855. this.angularSensibilityX = 1000.0;
  41856. this.angularSensibilityY = 1000.0;
  41857. this.pinchPrecision = 12.0;
  41858. /**
  41859. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41860. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41861. */
  41862. this.pinchDeltaPercentage = 0;
  41863. this.panningSensibility = 1000.0;
  41864. this.multiTouchPanning = true;
  41865. this.multiTouchPanAndZoom = true;
  41866. this._isPanClick = false;
  41867. this.pinchInwards = true;
  41868. }
  41869. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41870. var _this = this;
  41871. var engine = this.camera.getEngine();
  41872. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41873. var pointA = null;
  41874. var pointB = null;
  41875. var previousPinchSquaredDistance = 0;
  41876. var initialDistance = 0;
  41877. var twoFingerActivityCount = 0;
  41878. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41879. this._pointerInput = function (p, s) {
  41880. var evt = p.event;
  41881. var isTouch = p.event.pointerType === "touch";
  41882. if (engine.isInVRExclusivePointerMode) {
  41883. return;
  41884. }
  41885. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41886. return;
  41887. }
  41888. var srcElement = (evt.srcElement || evt.target);
  41889. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41890. try {
  41891. srcElement.setPointerCapture(evt.pointerId);
  41892. }
  41893. catch (e) {
  41894. //Nothing to do with the error. Execution will continue.
  41895. }
  41896. // Manage panning with pan button click
  41897. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41898. // manage pointers
  41899. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41900. if (pointA === null) {
  41901. pointA = cacheSoloPointer;
  41902. }
  41903. else if (pointB === null) {
  41904. pointB = cacheSoloPointer;
  41905. }
  41906. if (!noPreventDefault) {
  41907. evt.preventDefault();
  41908. element.focus();
  41909. }
  41910. }
  41911. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41912. _this.camera.restoreState();
  41913. }
  41914. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41915. try {
  41916. srcElement.releasePointerCapture(evt.pointerId);
  41917. }
  41918. catch (e) {
  41919. //Nothing to do with the error.
  41920. }
  41921. cacheSoloPointer = null;
  41922. previousPinchSquaredDistance = 0;
  41923. previousMultiTouchPanPosition.isPaning = false;
  41924. previousMultiTouchPanPosition.isPinching = false;
  41925. twoFingerActivityCount = 0;
  41926. initialDistance = 0;
  41927. if (!isTouch) {
  41928. pointB = null; // Mouse and pen are mono pointer
  41929. }
  41930. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41931. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41932. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41933. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41934. if (engine.badOS) {
  41935. pointA = pointB = null;
  41936. }
  41937. else {
  41938. //only remove the impacted pointer in case of multitouch allowing on most
  41939. //platforms switching from rotate to zoom and pan seamlessly.
  41940. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41941. pointA = pointB;
  41942. pointB = null;
  41943. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41944. }
  41945. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41946. pointB = null;
  41947. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41948. }
  41949. else {
  41950. pointA = pointB = null;
  41951. }
  41952. }
  41953. if (!noPreventDefault) {
  41954. evt.preventDefault();
  41955. }
  41956. }
  41957. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41958. if (!noPreventDefault) {
  41959. evt.preventDefault();
  41960. }
  41961. // One button down
  41962. if (pointA && pointB === null && cacheSoloPointer) {
  41963. if (_this.panningSensibility !== 0 &&
  41964. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41965. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41966. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41967. }
  41968. else {
  41969. var offsetX = evt.clientX - cacheSoloPointer.x;
  41970. var offsetY = evt.clientY - cacheSoloPointer.y;
  41971. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41972. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41973. }
  41974. cacheSoloPointer.x = evt.clientX;
  41975. cacheSoloPointer.y = evt.clientY;
  41976. }
  41977. else if (pointA && pointB) {
  41978. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41979. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41980. ed.x = evt.clientX;
  41981. ed.y = evt.clientY;
  41982. var direction = _this.pinchInwards ? 1 : -1;
  41983. var distX = pointA.x - pointB.x;
  41984. var distY = pointA.y - pointB.y;
  41985. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41986. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41987. if (previousPinchSquaredDistance === 0) {
  41988. initialDistance = pinchDistance;
  41989. previousPinchSquaredDistance = pinchSquaredDistance;
  41990. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41991. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41992. return;
  41993. }
  41994. if (_this.multiTouchPanAndZoom) {
  41995. if (_this.pinchDeltaPercentage) {
  41996. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41997. }
  41998. else {
  41999. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  42000. (_this.pinchPrecision *
  42001. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  42002. direction);
  42003. }
  42004. if (_this.panningSensibility !== 0) {
  42005. var pointersCenterX = (pointA.x + pointB.x) / 2;
  42006. var pointersCenterY = (pointA.y + pointB.y) / 2;
  42007. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  42008. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  42009. previousMultiTouchPanPosition.x = pointersCenterX;
  42010. previousMultiTouchPanPosition.y = pointersCenterY;
  42011. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  42012. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  42013. }
  42014. }
  42015. else {
  42016. twoFingerActivityCount++;
  42017. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  42018. if (_this.pinchDeltaPercentage) {
  42019. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  42020. }
  42021. else {
  42022. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  42023. (_this.pinchPrecision *
  42024. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  42025. direction);
  42026. }
  42027. previousMultiTouchPanPosition.isPaning = false;
  42028. previousMultiTouchPanPosition.isPinching = true;
  42029. }
  42030. else {
  42031. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  42032. if (!previousMultiTouchPanPosition.isPaning) {
  42033. previousMultiTouchPanPosition.isPaning = true;
  42034. previousMultiTouchPanPosition.isPinching = false;
  42035. previousMultiTouchPanPosition.x = ed.x;
  42036. previousMultiTouchPanPosition.y = ed.y;
  42037. return;
  42038. }
  42039. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  42040. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  42041. }
  42042. }
  42043. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  42044. previousMultiTouchPanPosition.x = ed.x;
  42045. previousMultiTouchPanPosition.y = ed.y;
  42046. }
  42047. }
  42048. previousPinchSquaredDistance = pinchSquaredDistance;
  42049. }
  42050. }
  42051. };
  42052. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  42053. this._onContextMenu = function (evt) {
  42054. evt.preventDefault();
  42055. };
  42056. if (!this.camera._useCtrlForPanning) {
  42057. element.addEventListener("contextmenu", this._onContextMenu, false);
  42058. }
  42059. this._onLostFocus = function () {
  42060. //this._keys = [];
  42061. pointA = pointB = null;
  42062. previousPinchSquaredDistance = 0;
  42063. previousMultiTouchPanPosition.isPaning = false;
  42064. previousMultiTouchPanPosition.isPinching = false;
  42065. twoFingerActivityCount = 0;
  42066. cacheSoloPointer = null;
  42067. initialDistance = 0;
  42068. };
  42069. this._onMouseMove = function (evt) {
  42070. if (!engine.isPointerLock) {
  42071. return;
  42072. }
  42073. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42074. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42075. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  42076. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  42077. if (!noPreventDefault) {
  42078. evt.preventDefault();
  42079. }
  42080. };
  42081. this._onGestureStart = function (e) {
  42082. if (window.MSGesture === undefined) {
  42083. return;
  42084. }
  42085. if (!_this._MSGestureHandler) {
  42086. _this._MSGestureHandler = new MSGesture();
  42087. _this._MSGestureHandler.target = element;
  42088. }
  42089. _this._MSGestureHandler.addPointer(e.pointerId);
  42090. };
  42091. this._onGesture = function (e) {
  42092. _this.camera.radius *= e.scale;
  42093. if (e.preventDefault) {
  42094. if (!noPreventDefault) {
  42095. e.stopPropagation();
  42096. e.preventDefault();
  42097. }
  42098. }
  42099. };
  42100. element.addEventListener("mousemove", this._onMouseMove, false);
  42101. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  42102. element.addEventListener("MSGestureChange", this._onGesture, false);
  42103. BABYLON.Tools.RegisterTopRootEvents([
  42104. { name: "blur", handler: this._onLostFocus }
  42105. ]);
  42106. };
  42107. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  42108. if (this._onLostFocus) {
  42109. BABYLON.Tools.UnregisterTopRootEvents([
  42110. { name: "blur", handler: this._onLostFocus }
  42111. ]);
  42112. }
  42113. if (element && this._observer) {
  42114. this.camera.getScene().onPointerObservable.remove(this._observer);
  42115. this._observer = null;
  42116. if (this._onContextMenu) {
  42117. element.removeEventListener("contextmenu", this._onContextMenu);
  42118. }
  42119. if (this._onMouseMove) {
  42120. element.removeEventListener("mousemove", this._onMouseMove);
  42121. }
  42122. if (this._onGestureStart) {
  42123. element.removeEventListener("MSPointerDown", this._onGestureStart);
  42124. }
  42125. if (this._onGesture) {
  42126. element.removeEventListener("MSGestureChange", this._onGesture);
  42127. }
  42128. this._isPanClick = false;
  42129. this.pinchInwards = true;
  42130. this._onMouseMove = null;
  42131. this._onGestureStart = null;
  42132. this._onGesture = null;
  42133. this._MSGestureHandler = null;
  42134. this._onLostFocus = null;
  42135. this._onContextMenu = null;
  42136. }
  42137. };
  42138. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  42139. return "ArcRotateCameraPointersInput";
  42140. };
  42141. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  42142. return "pointers";
  42143. };
  42144. __decorate([
  42145. BABYLON.serialize()
  42146. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  42147. __decorate([
  42148. BABYLON.serialize()
  42149. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  42150. __decorate([
  42151. BABYLON.serialize()
  42152. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  42153. __decorate([
  42154. BABYLON.serialize()
  42155. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  42156. __decorate([
  42157. BABYLON.serialize()
  42158. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  42159. __decorate([
  42160. BABYLON.serialize()
  42161. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  42162. __decorate([
  42163. BABYLON.serialize()
  42164. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  42165. __decorate([
  42166. BABYLON.serialize()
  42167. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  42168. return ArcRotateCameraPointersInput;
  42169. }());
  42170. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  42171. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  42172. })(BABYLON || (BABYLON = {}));
  42173. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42174. var BABYLON;
  42175. (function (BABYLON) {
  42176. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42177. __extends(ArcRotateCameraInputsManager, _super);
  42178. function ArcRotateCameraInputsManager(camera) {
  42179. return _super.call(this, camera) || this;
  42180. }
  42181. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42182. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42183. return this;
  42184. };
  42185. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42186. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42187. return this;
  42188. };
  42189. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42190. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42191. return this;
  42192. };
  42193. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42194. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42195. return this;
  42196. };
  42197. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42198. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42199. return this;
  42200. };
  42201. return ArcRotateCameraInputsManager;
  42202. }(BABYLON.CameraInputsManager));
  42203. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42204. })(BABYLON || (BABYLON = {}));
  42205. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42206. var BABYLON;
  42207. (function (BABYLON) {
  42208. var ArcRotateCamera = /** @class */ (function (_super) {
  42209. __extends(ArcRotateCamera, _super);
  42210. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42211. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42212. _this.inertialAlphaOffset = 0;
  42213. _this.inertialBetaOffset = 0;
  42214. _this.inertialRadiusOffset = 0;
  42215. _this.lowerAlphaLimit = null;
  42216. _this.upperAlphaLimit = null;
  42217. _this.lowerBetaLimit = 0.01;
  42218. _this.upperBetaLimit = Math.PI;
  42219. _this.lowerRadiusLimit = null;
  42220. _this.upperRadiusLimit = null;
  42221. _this.inertialPanningX = 0;
  42222. _this.inertialPanningY = 0;
  42223. _this.pinchToPanMaxDistance = 20;
  42224. _this.panningDistanceLimit = null;
  42225. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42226. _this.panningInertia = 0.9;
  42227. //-- end properties for backward compatibility for inputs
  42228. _this.zoomOnFactor = 1;
  42229. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42230. _this.allowUpsideDown = true;
  42231. _this._viewMatrix = new BABYLON.Matrix();
  42232. // Panning
  42233. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42234. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42235. _this.checkCollisions = false;
  42236. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42237. _this._previousPosition = BABYLON.Vector3.Zero();
  42238. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42239. _this._newPosition = BABYLON.Vector3.Zero();
  42240. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42241. if (collidedMesh === void 0) { collidedMesh = null; }
  42242. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42243. newPosition.multiplyInPlace(_this._collider._radius);
  42244. }
  42245. if (!collidedMesh) {
  42246. _this._previousPosition.copyFrom(_this.position);
  42247. }
  42248. else {
  42249. _this.setPosition(newPosition);
  42250. if (_this.onCollide) {
  42251. _this.onCollide(collidedMesh);
  42252. }
  42253. }
  42254. // Recompute because of constraints
  42255. var cosa = Math.cos(_this.alpha);
  42256. var sina = Math.sin(_this.alpha);
  42257. var cosb = Math.cos(_this.beta);
  42258. var sinb = Math.sin(_this.beta);
  42259. if (sinb === 0) {
  42260. sinb = 0.0001;
  42261. }
  42262. var target = _this._getTargetPosition();
  42263. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42264. _this.position.copyFrom(_this._newPosition);
  42265. var up = _this.upVector;
  42266. if (_this.allowUpsideDown && _this.beta < 0) {
  42267. up = up.clone();
  42268. up = up.negate();
  42269. }
  42270. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42271. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42272. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42273. _this._collisionTriggered = false;
  42274. };
  42275. _this._target = BABYLON.Vector3.Zero();
  42276. if (target) {
  42277. _this.setTarget(target);
  42278. }
  42279. _this.alpha = alpha;
  42280. _this.beta = beta;
  42281. _this.radius = radius;
  42282. _this.getViewMatrix();
  42283. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42284. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42285. return _this;
  42286. }
  42287. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42288. get: function () {
  42289. return this._target;
  42290. },
  42291. set: function (value) {
  42292. this.setTarget(value);
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42298. //-- begin properties for backward compatibility for inputs
  42299. get: function () {
  42300. var pointers = this.inputs.attached["pointers"];
  42301. if (pointers)
  42302. return pointers.angularSensibilityX;
  42303. return 0;
  42304. },
  42305. set: function (value) {
  42306. var pointers = this.inputs.attached["pointers"];
  42307. if (pointers) {
  42308. pointers.angularSensibilityX = value;
  42309. }
  42310. },
  42311. enumerable: true,
  42312. configurable: true
  42313. });
  42314. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42315. get: function () {
  42316. var pointers = this.inputs.attached["pointers"];
  42317. if (pointers)
  42318. return pointers.angularSensibilityY;
  42319. return 0;
  42320. },
  42321. set: function (value) {
  42322. var pointers = this.inputs.attached["pointers"];
  42323. if (pointers) {
  42324. pointers.angularSensibilityY = value;
  42325. }
  42326. },
  42327. enumerable: true,
  42328. configurable: true
  42329. });
  42330. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42331. get: function () {
  42332. var pointers = this.inputs.attached["pointers"];
  42333. if (pointers)
  42334. return pointers.pinchPrecision;
  42335. return 0;
  42336. },
  42337. set: function (value) {
  42338. var pointers = this.inputs.attached["pointers"];
  42339. if (pointers) {
  42340. pointers.pinchPrecision = value;
  42341. }
  42342. },
  42343. enumerable: true,
  42344. configurable: true
  42345. });
  42346. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42347. get: function () {
  42348. var pointers = this.inputs.attached["pointers"];
  42349. if (pointers)
  42350. return pointers.pinchDeltaPercentage;
  42351. return 0;
  42352. },
  42353. set: function (value) {
  42354. var pointers = this.inputs.attached["pointers"];
  42355. if (pointers) {
  42356. pointers.pinchDeltaPercentage = value;
  42357. }
  42358. },
  42359. enumerable: true,
  42360. configurable: true
  42361. });
  42362. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42363. get: function () {
  42364. var pointers = this.inputs.attached["pointers"];
  42365. if (pointers)
  42366. return pointers.panningSensibility;
  42367. return 0;
  42368. },
  42369. set: function (value) {
  42370. var pointers = this.inputs.attached["pointers"];
  42371. if (pointers) {
  42372. pointers.panningSensibility = value;
  42373. }
  42374. },
  42375. enumerable: true,
  42376. configurable: true
  42377. });
  42378. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42379. get: function () {
  42380. var keyboard = this.inputs.attached["keyboard"];
  42381. if (keyboard)
  42382. return keyboard.keysUp;
  42383. return [];
  42384. },
  42385. set: function (value) {
  42386. var keyboard = this.inputs.attached["keyboard"];
  42387. if (keyboard)
  42388. keyboard.keysUp = value;
  42389. },
  42390. enumerable: true,
  42391. configurable: true
  42392. });
  42393. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42394. get: function () {
  42395. var keyboard = this.inputs.attached["keyboard"];
  42396. if (keyboard)
  42397. return keyboard.keysDown;
  42398. return [];
  42399. },
  42400. set: function (value) {
  42401. var keyboard = this.inputs.attached["keyboard"];
  42402. if (keyboard)
  42403. keyboard.keysDown = value;
  42404. },
  42405. enumerable: true,
  42406. configurable: true
  42407. });
  42408. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42409. get: function () {
  42410. var keyboard = this.inputs.attached["keyboard"];
  42411. if (keyboard)
  42412. return keyboard.keysLeft;
  42413. return [];
  42414. },
  42415. set: function (value) {
  42416. var keyboard = this.inputs.attached["keyboard"];
  42417. if (keyboard)
  42418. keyboard.keysLeft = value;
  42419. },
  42420. enumerable: true,
  42421. configurable: true
  42422. });
  42423. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42424. get: function () {
  42425. var keyboard = this.inputs.attached["keyboard"];
  42426. if (keyboard)
  42427. return keyboard.keysRight;
  42428. return [];
  42429. },
  42430. set: function (value) {
  42431. var keyboard = this.inputs.attached["keyboard"];
  42432. if (keyboard)
  42433. keyboard.keysRight = value;
  42434. },
  42435. enumerable: true,
  42436. configurable: true
  42437. });
  42438. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42439. get: function () {
  42440. var mousewheel = this.inputs.attached["mousewheel"];
  42441. if (mousewheel)
  42442. return mousewheel.wheelPrecision;
  42443. return 0;
  42444. },
  42445. set: function (value) {
  42446. var mousewheel = this.inputs.attached["mousewheel"];
  42447. if (mousewheel)
  42448. mousewheel.wheelPrecision = value;
  42449. },
  42450. enumerable: true,
  42451. configurable: true
  42452. });
  42453. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42454. get: function () {
  42455. var mousewheel = this.inputs.attached["mousewheel"];
  42456. if (mousewheel)
  42457. return mousewheel.wheelDeltaPercentage;
  42458. return 0;
  42459. },
  42460. set: function (value) {
  42461. var mousewheel = this.inputs.attached["mousewheel"];
  42462. if (mousewheel)
  42463. mousewheel.wheelDeltaPercentage = value;
  42464. },
  42465. enumerable: true,
  42466. configurable: true
  42467. });
  42468. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42469. get: function () {
  42470. return this._bouncingBehavior;
  42471. },
  42472. enumerable: true,
  42473. configurable: true
  42474. });
  42475. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42476. get: function () {
  42477. return this._bouncingBehavior != null;
  42478. },
  42479. set: function (value) {
  42480. if (value === this.useBouncingBehavior) {
  42481. return;
  42482. }
  42483. if (value) {
  42484. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42485. this.addBehavior(this._bouncingBehavior);
  42486. }
  42487. else if (this._bouncingBehavior) {
  42488. this.removeBehavior(this._bouncingBehavior);
  42489. this._bouncingBehavior = null;
  42490. }
  42491. },
  42492. enumerable: true,
  42493. configurable: true
  42494. });
  42495. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42496. get: function () {
  42497. return this._framingBehavior;
  42498. },
  42499. enumerable: true,
  42500. configurable: true
  42501. });
  42502. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42503. get: function () {
  42504. return this._framingBehavior != null;
  42505. },
  42506. set: function (value) {
  42507. if (value === this.useFramingBehavior) {
  42508. return;
  42509. }
  42510. if (value) {
  42511. this._framingBehavior = new BABYLON.FramingBehavior();
  42512. this.addBehavior(this._framingBehavior);
  42513. }
  42514. else if (this._framingBehavior) {
  42515. this.removeBehavior(this._framingBehavior);
  42516. this._framingBehavior = null;
  42517. }
  42518. },
  42519. enumerable: true,
  42520. configurable: true
  42521. });
  42522. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42523. get: function () {
  42524. return this._autoRotationBehavior;
  42525. },
  42526. enumerable: true,
  42527. configurable: true
  42528. });
  42529. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42530. get: function () {
  42531. return this._autoRotationBehavior != null;
  42532. },
  42533. set: function (value) {
  42534. if (value === this.useAutoRotationBehavior) {
  42535. return;
  42536. }
  42537. if (value) {
  42538. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42539. this.addBehavior(this._autoRotationBehavior);
  42540. }
  42541. else if (this._autoRotationBehavior) {
  42542. this.removeBehavior(this._autoRotationBehavior);
  42543. this._autoRotationBehavior = null;
  42544. }
  42545. },
  42546. enumerable: true,
  42547. configurable: true
  42548. });
  42549. // Cache
  42550. ArcRotateCamera.prototype._initCache = function () {
  42551. _super.prototype._initCache.call(this);
  42552. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42553. this._cache.alpha = undefined;
  42554. this._cache.beta = undefined;
  42555. this._cache.radius = undefined;
  42556. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42557. };
  42558. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42559. if (!ignoreParentClass) {
  42560. _super.prototype._updateCache.call(this);
  42561. }
  42562. this._cache._target.copyFrom(this._getTargetPosition());
  42563. this._cache.alpha = this.alpha;
  42564. this._cache.beta = this.beta;
  42565. this._cache.radius = this.radius;
  42566. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42567. };
  42568. ArcRotateCamera.prototype._getTargetPosition = function () {
  42569. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42570. var pos = this._targetHost.getAbsolutePosition();
  42571. if (this._targetBoundingCenter) {
  42572. pos.addToRef(this._targetBoundingCenter, this._target);
  42573. }
  42574. else {
  42575. this._target.copyFrom(pos);
  42576. }
  42577. }
  42578. var lockedTargetPosition = this._getLockedTargetPosition();
  42579. if (lockedTargetPosition) {
  42580. return lockedTargetPosition;
  42581. }
  42582. return this._target;
  42583. };
  42584. ArcRotateCamera.prototype.storeState = function () {
  42585. this._storedAlpha = this.alpha;
  42586. this._storedBeta = this.beta;
  42587. this._storedRadius = this.radius;
  42588. this._storedTarget = this._getTargetPosition().clone();
  42589. return _super.prototype.storeState.call(this);
  42590. };
  42591. /**
  42592. * Restored camera state. You must call storeState() first
  42593. */
  42594. ArcRotateCamera.prototype._restoreStateValues = function () {
  42595. if (!_super.prototype._restoreStateValues.call(this)) {
  42596. return false;
  42597. }
  42598. this.alpha = this._storedAlpha;
  42599. this.beta = this._storedBeta;
  42600. this.radius = this._storedRadius;
  42601. this.setTarget(this._storedTarget.clone());
  42602. this.inertialAlphaOffset = 0;
  42603. this.inertialBetaOffset = 0;
  42604. this.inertialRadiusOffset = 0;
  42605. this.inertialPanningX = 0;
  42606. this.inertialPanningY = 0;
  42607. return true;
  42608. };
  42609. // Synchronized
  42610. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42611. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42612. return false;
  42613. return this._cache._target.equals(this._getTargetPosition())
  42614. && this._cache.alpha === this.alpha
  42615. && this._cache.beta === this.beta
  42616. && this._cache.radius === this.radius
  42617. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42618. };
  42619. // Methods
  42620. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42621. var _this = this;
  42622. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42623. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42624. this._useCtrlForPanning = useCtrlForPanning;
  42625. this._panningMouseButton = panningMouseButton;
  42626. this.inputs.attachElement(element, noPreventDefault);
  42627. this._reset = function () {
  42628. _this.inertialAlphaOffset = 0;
  42629. _this.inertialBetaOffset = 0;
  42630. _this.inertialRadiusOffset = 0;
  42631. _this.inertialPanningX = 0;
  42632. _this.inertialPanningY = 0;
  42633. };
  42634. };
  42635. ArcRotateCamera.prototype.detachControl = function (element) {
  42636. this.inputs.detachElement(element);
  42637. if (this._reset) {
  42638. this._reset();
  42639. }
  42640. };
  42641. ArcRotateCamera.prototype._checkInputs = function () {
  42642. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42643. if (this._collisionTriggered) {
  42644. return;
  42645. }
  42646. this.inputs.checkInputs();
  42647. // Inertia
  42648. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42649. if (this.getScene().useRightHandedSystem) {
  42650. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42651. }
  42652. else {
  42653. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42654. }
  42655. this.beta += this.inertialBetaOffset;
  42656. this.radius -= this.inertialRadiusOffset;
  42657. this.inertialAlphaOffset *= this.inertia;
  42658. this.inertialBetaOffset *= this.inertia;
  42659. this.inertialRadiusOffset *= this.inertia;
  42660. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42661. this.inertialAlphaOffset = 0;
  42662. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42663. this.inertialBetaOffset = 0;
  42664. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42665. this.inertialRadiusOffset = 0;
  42666. }
  42667. // Panning inertia
  42668. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42669. if (!this._localDirection) {
  42670. this._localDirection = BABYLON.Vector3.Zero();
  42671. this._transformedDirection = BABYLON.Vector3.Zero();
  42672. }
  42673. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42674. this._localDirection.multiplyInPlace(this.panningAxis);
  42675. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42676. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42677. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42678. if (!this.panningAxis.y) {
  42679. this._transformedDirection.y = 0;
  42680. }
  42681. if (!this._targetHost) {
  42682. if (this.panningDistanceLimit) {
  42683. this._transformedDirection.addInPlace(this._target);
  42684. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42685. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42686. this._target.copyFrom(this._transformedDirection);
  42687. }
  42688. }
  42689. else {
  42690. this._target.addInPlace(this._transformedDirection);
  42691. }
  42692. }
  42693. this.inertialPanningX *= this.panningInertia;
  42694. this.inertialPanningY *= this.panningInertia;
  42695. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42696. this.inertialPanningX = 0;
  42697. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42698. this.inertialPanningY = 0;
  42699. }
  42700. // Limits
  42701. this._checkLimits();
  42702. _super.prototype._checkInputs.call(this);
  42703. };
  42704. ArcRotateCamera.prototype._checkLimits = function () {
  42705. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42706. if (this.allowUpsideDown && this.beta > Math.PI) {
  42707. this.beta = this.beta - (2 * Math.PI);
  42708. }
  42709. }
  42710. else {
  42711. if (this.beta < this.lowerBetaLimit) {
  42712. this.beta = this.lowerBetaLimit;
  42713. }
  42714. }
  42715. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42716. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42717. this.beta = this.beta + (2 * Math.PI);
  42718. }
  42719. }
  42720. else {
  42721. if (this.beta > this.upperBetaLimit) {
  42722. this.beta = this.upperBetaLimit;
  42723. }
  42724. }
  42725. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42726. this.alpha = this.lowerAlphaLimit;
  42727. }
  42728. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42729. this.alpha = this.upperAlphaLimit;
  42730. }
  42731. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42732. this.radius = this.lowerRadiusLimit;
  42733. }
  42734. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42735. this.radius = this.upperRadiusLimit;
  42736. }
  42737. };
  42738. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42739. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42740. this.radius = radiusv3.length();
  42741. if (this.radius === 0) {
  42742. this.radius = 0.0001; // Just to avoid division by zero
  42743. }
  42744. // Alpha
  42745. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42746. if (radiusv3.z < 0) {
  42747. this.alpha = 2 * Math.PI - this.alpha;
  42748. }
  42749. // Beta
  42750. this.beta = Math.acos(radiusv3.y / this.radius);
  42751. this._checkLimits();
  42752. };
  42753. ArcRotateCamera.prototype.setPosition = function (position) {
  42754. if (this.position.equals(position)) {
  42755. return;
  42756. }
  42757. this.position.copyFrom(position);
  42758. this.rebuildAnglesAndRadius();
  42759. };
  42760. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42761. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42762. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42763. if (target.getBoundingInfo) {
  42764. if (toBoundingCenter) {
  42765. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42766. }
  42767. else {
  42768. this._targetBoundingCenter = null;
  42769. }
  42770. this._targetHost = target;
  42771. this._target = this._getTargetPosition();
  42772. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42773. }
  42774. else {
  42775. var newTarget = target;
  42776. var currentTarget = this._getTargetPosition();
  42777. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42778. return;
  42779. }
  42780. this._targetHost = null;
  42781. this._target = newTarget;
  42782. this._targetBoundingCenter = null;
  42783. this.onMeshTargetChangedObservable.notifyObservers(null);
  42784. }
  42785. this.rebuildAnglesAndRadius();
  42786. };
  42787. ArcRotateCamera.prototype._getViewMatrix = function () {
  42788. // Compute
  42789. var cosa = Math.cos(this.alpha);
  42790. var sina = Math.sin(this.alpha);
  42791. var cosb = Math.cos(this.beta);
  42792. var sinb = Math.sin(this.beta);
  42793. if (sinb === 0) {
  42794. sinb = 0.0001;
  42795. }
  42796. var target = this._getTargetPosition();
  42797. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42798. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42799. if (!this._collider) {
  42800. this._collider = new BABYLON.Collider();
  42801. }
  42802. this._collider._radius = this.collisionRadius;
  42803. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42804. this._collisionTriggered = true;
  42805. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42806. }
  42807. else {
  42808. this.position.copyFrom(this._newPosition);
  42809. var up = this.upVector;
  42810. if (this.allowUpsideDown && sinb < 0) {
  42811. up = up.clone();
  42812. up = up.negate();
  42813. }
  42814. if (this.getScene().useRightHandedSystem) {
  42815. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42816. }
  42817. else {
  42818. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42819. }
  42820. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42821. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42822. }
  42823. this._currentTarget = target;
  42824. return this._viewMatrix;
  42825. };
  42826. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42827. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42828. meshes = meshes || this.getScene().meshes;
  42829. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42830. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42831. this.radius = distance * this.zoomOnFactor;
  42832. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42833. };
  42834. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42835. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42836. var meshesOrMinMaxVector;
  42837. var distance;
  42838. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42839. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42840. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42841. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42842. }
  42843. else {
  42844. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42845. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42846. distance = minMaxVectorAndDistance.distance;
  42847. }
  42848. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42849. if (!doNotUpdateMaxZ) {
  42850. this.maxZ = distance * 2;
  42851. }
  42852. };
  42853. /**
  42854. * @override
  42855. * Override Camera.createRigCamera
  42856. */
  42857. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42858. var alphaShift = 0;
  42859. switch (this.cameraRigMode) {
  42860. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42861. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42862. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42863. case BABYLON.Camera.RIG_MODE_VR:
  42864. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42865. break;
  42866. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42867. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42868. break;
  42869. }
  42870. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42871. rigCam._cameraRigParams = {};
  42872. return rigCam;
  42873. };
  42874. /**
  42875. * @override
  42876. * Override Camera._updateRigCameras
  42877. */
  42878. ArcRotateCamera.prototype._updateRigCameras = function () {
  42879. var camLeft = this._rigCameras[0];
  42880. var camRight = this._rigCameras[1];
  42881. camLeft.beta = camRight.beta = this.beta;
  42882. camLeft.radius = camRight.radius = this.radius;
  42883. switch (this.cameraRigMode) {
  42884. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42885. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42886. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42887. case BABYLON.Camera.RIG_MODE_VR:
  42888. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42889. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42890. break;
  42891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42892. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42893. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42894. break;
  42895. }
  42896. _super.prototype._updateRigCameras.call(this);
  42897. };
  42898. ArcRotateCamera.prototype.dispose = function () {
  42899. this.inputs.clear();
  42900. _super.prototype.dispose.call(this);
  42901. };
  42902. ArcRotateCamera.prototype.getClassName = function () {
  42903. return "ArcRotateCamera";
  42904. };
  42905. __decorate([
  42906. BABYLON.serialize()
  42907. ], ArcRotateCamera.prototype, "alpha", void 0);
  42908. __decorate([
  42909. BABYLON.serialize()
  42910. ], ArcRotateCamera.prototype, "beta", void 0);
  42911. __decorate([
  42912. BABYLON.serialize()
  42913. ], ArcRotateCamera.prototype, "radius", void 0);
  42914. __decorate([
  42915. BABYLON.serializeAsVector3("target")
  42916. ], ArcRotateCamera.prototype, "_target", void 0);
  42917. __decorate([
  42918. BABYLON.serialize()
  42919. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42920. __decorate([
  42921. BABYLON.serialize()
  42922. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42923. __decorate([
  42924. BABYLON.serialize()
  42925. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42926. __decorate([
  42927. BABYLON.serialize()
  42928. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42929. __decorate([
  42930. BABYLON.serialize()
  42931. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42932. __decorate([
  42933. BABYLON.serialize()
  42934. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42935. __decorate([
  42936. BABYLON.serialize()
  42937. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42938. __decorate([
  42939. BABYLON.serialize()
  42940. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42941. __decorate([
  42942. BABYLON.serialize()
  42943. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42944. __decorate([
  42945. BABYLON.serialize()
  42946. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42947. __decorate([
  42948. BABYLON.serialize()
  42949. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42950. __decorate([
  42951. BABYLON.serialize()
  42952. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42953. __decorate([
  42954. BABYLON.serialize()
  42955. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42956. __decorate([
  42957. BABYLON.serializeAsVector3()
  42958. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42959. __decorate([
  42960. BABYLON.serialize()
  42961. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42962. __decorate([
  42963. BABYLON.serialize()
  42964. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42965. __decorate([
  42966. BABYLON.serialize()
  42967. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42968. return ArcRotateCamera;
  42969. }(BABYLON.TargetCamera));
  42970. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42971. })(BABYLON || (BABYLON = {}));
  42972. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42973. var BABYLON;
  42974. (function (BABYLON) {
  42975. /**
  42976. * The HemisphericLight simulates the ambient environment light,
  42977. * so the passed direction is the light reflection direction, not the incoming direction.
  42978. */
  42979. var HemisphericLight = /** @class */ (function (_super) {
  42980. __extends(HemisphericLight, _super);
  42981. /**
  42982. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42983. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42984. * The HemisphericLight can't cast shadows.
  42985. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42986. * @param name The friendly name of the light
  42987. * @param direction The direction of the light reflection
  42988. * @param scene The scene the light belongs to
  42989. */
  42990. function HemisphericLight(name, direction, scene) {
  42991. var _this = _super.call(this, name, scene) || this;
  42992. /**
  42993. * The groundColor is the light in the opposite direction to the one specified during creation.
  42994. * 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.
  42995. */
  42996. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42997. _this.direction = direction || BABYLON.Vector3.Up();
  42998. return _this;
  42999. }
  43000. HemisphericLight.prototype._buildUniformLayout = function () {
  43001. this._uniformBuffer.addUniform("vLightData", 4);
  43002. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43003. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43004. this._uniformBuffer.addUniform("vLightGround", 3);
  43005. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43006. this._uniformBuffer.addUniform("depthValues", 2);
  43007. this._uniformBuffer.create();
  43008. };
  43009. /**
  43010. * Returns the string "HemisphericLight".
  43011. * @return The class name
  43012. */
  43013. HemisphericLight.prototype.getClassName = function () {
  43014. return "HemisphericLight";
  43015. };
  43016. /**
  43017. * Sets the HemisphericLight direction towards the passed target (Vector3).
  43018. * Returns the updated direction.
  43019. * @param target The target the direction should point to
  43020. * @return The computed direction
  43021. */
  43022. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  43023. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  43024. return this.direction;
  43025. };
  43026. /**
  43027. * Returns the shadow generator associated to the light.
  43028. * @returns Always null for hemispheric lights because it does not support shadows.
  43029. */
  43030. HemisphericLight.prototype.getShadowGenerator = function () {
  43031. return null;
  43032. };
  43033. /**
  43034. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  43035. * @param effect The effect to update
  43036. * @param lightIndex The index of the light in the effect to update
  43037. * @returns The hemispheric light
  43038. */
  43039. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  43040. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43041. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  43042. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  43043. return this;
  43044. };
  43045. /**
  43046. * @ignore internal use only.
  43047. */
  43048. HemisphericLight.prototype._getWorldMatrix = function () {
  43049. if (!this._worldMatrix) {
  43050. this._worldMatrix = BABYLON.Matrix.Identity();
  43051. }
  43052. return this._worldMatrix;
  43053. };
  43054. /**
  43055. * Returns the integer 3.
  43056. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43057. */
  43058. HemisphericLight.prototype.getTypeID = function () {
  43059. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  43060. };
  43061. __decorate([
  43062. BABYLON.serializeAsColor3()
  43063. ], HemisphericLight.prototype, "groundColor", void 0);
  43064. __decorate([
  43065. BABYLON.serializeAsVector3()
  43066. ], HemisphericLight.prototype, "direction", void 0);
  43067. return HemisphericLight;
  43068. }(BABYLON.Light));
  43069. BABYLON.HemisphericLight = HemisphericLight;
  43070. })(BABYLON || (BABYLON = {}));
  43071. //# sourceMappingURL=babylon.hemisphericLight.js.map
  43072. var BABYLON;
  43073. (function (BABYLON) {
  43074. /**
  43075. * Base implementation of @see IShadowLight
  43076. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  43077. */
  43078. var ShadowLight = /** @class */ (function (_super) {
  43079. __extends(ShadowLight, _super);
  43080. function ShadowLight() {
  43081. var _this = _super !== null && _super.apply(this, arguments) || this;
  43082. _this._needProjectionMatrixCompute = true;
  43083. return _this;
  43084. }
  43085. ShadowLight.prototype._setPosition = function (value) {
  43086. this._position = value;
  43087. };
  43088. Object.defineProperty(ShadowLight.prototype, "position", {
  43089. /**
  43090. * Sets the position the shadow will be casted from. Also use as the light position for both
  43091. * point and spot lights.
  43092. */
  43093. get: function () {
  43094. return this._position;
  43095. },
  43096. /**
  43097. * Sets the position the shadow will be casted from. Also use as the light position for both
  43098. * point and spot lights.
  43099. */
  43100. set: function (value) {
  43101. this._setPosition(value);
  43102. },
  43103. enumerable: true,
  43104. configurable: true
  43105. });
  43106. ShadowLight.prototype._setDirection = function (value) {
  43107. this._direction = value;
  43108. };
  43109. Object.defineProperty(ShadowLight.prototype, "direction", {
  43110. /**
  43111. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43112. * Also use as the light direction on spot and directional lights.
  43113. */
  43114. get: function () {
  43115. return this._direction;
  43116. },
  43117. /**
  43118. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  43119. * Also use as the light direction on spot and directional lights.
  43120. */
  43121. set: function (value) {
  43122. this._setDirection(value);
  43123. },
  43124. enumerable: true,
  43125. configurable: true
  43126. });
  43127. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  43128. /**
  43129. * Gets the shadow projection clipping minimum z value.
  43130. */
  43131. get: function () {
  43132. return this._shadowMinZ;
  43133. },
  43134. /**
  43135. * Sets the shadow projection clipping minimum z value.
  43136. */
  43137. set: function (value) {
  43138. this._shadowMinZ = value;
  43139. this.forceProjectionMatrixCompute();
  43140. },
  43141. enumerable: true,
  43142. configurable: true
  43143. });
  43144. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  43145. /**
  43146. * Sets the shadow projection clipping maximum z value.
  43147. */
  43148. get: function () {
  43149. return this._shadowMaxZ;
  43150. },
  43151. /**
  43152. * Gets the shadow projection clipping maximum z value.
  43153. */
  43154. set: function (value) {
  43155. this._shadowMaxZ = value;
  43156. this.forceProjectionMatrixCompute();
  43157. },
  43158. enumerable: true,
  43159. configurable: true
  43160. });
  43161. /**
  43162. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  43163. * @returns true if the information has been computed, false if it does not need to (no parenting)
  43164. */
  43165. ShadowLight.prototype.computeTransformedInformation = function () {
  43166. if (this.parent && this.parent.getWorldMatrix) {
  43167. if (!this.transformedPosition) {
  43168. this.transformedPosition = BABYLON.Vector3.Zero();
  43169. }
  43170. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  43171. // In case the direction is present.
  43172. if (this.direction) {
  43173. if (!this.transformedDirection) {
  43174. this.transformedDirection = BABYLON.Vector3.Zero();
  43175. }
  43176. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  43177. }
  43178. return true;
  43179. }
  43180. return false;
  43181. };
  43182. /**
  43183. * Return the depth scale used for the shadow map.
  43184. * @returns the depth scale.
  43185. */
  43186. ShadowLight.prototype.getDepthScale = function () {
  43187. return 50.0;
  43188. };
  43189. /**
  43190. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  43191. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43192. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43193. */
  43194. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  43195. return this.transformedDirection ? this.transformedDirection : this.direction;
  43196. };
  43197. /**
  43198. * Returns the ShadowLight absolute position in the World.
  43199. * @returns the position vector in world space
  43200. */
  43201. ShadowLight.prototype.getAbsolutePosition = function () {
  43202. return this.transformedPosition ? this.transformedPosition : this.position;
  43203. };
  43204. /**
  43205. * Sets the ShadowLight direction toward the passed target.
  43206. * @param target The point tot target in local space
  43207. * @returns the updated ShadowLight direction
  43208. */
  43209. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43210. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43211. return this.direction;
  43212. };
  43213. /**
  43214. * Returns the light rotation in euler definition.
  43215. * @returns the x y z rotation in local space.
  43216. */
  43217. ShadowLight.prototype.getRotation = function () {
  43218. this.direction.normalize();
  43219. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43220. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43221. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43222. };
  43223. /**
  43224. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43225. * @returns true if a cube texture needs to be use
  43226. */
  43227. ShadowLight.prototype.needCube = function () {
  43228. return false;
  43229. };
  43230. /**
  43231. * Detects if the projection matrix requires to be recomputed this frame.
  43232. * @returns true if it requires to be recomputed otherwise, false.
  43233. */
  43234. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43235. return this._needProjectionMatrixCompute;
  43236. };
  43237. /**
  43238. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43239. */
  43240. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43241. this._needProjectionMatrixCompute = true;
  43242. };
  43243. /**
  43244. * Get the world matrix of the sahdow lights.
  43245. * @ignore Internal Use Only
  43246. */
  43247. ShadowLight.prototype._getWorldMatrix = function () {
  43248. if (!this._worldMatrix) {
  43249. this._worldMatrix = BABYLON.Matrix.Identity();
  43250. }
  43251. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43252. return this._worldMatrix;
  43253. };
  43254. /**
  43255. * Gets the minZ used for shadow according to both the scene and the light.
  43256. * @param activeCamera The camera we are returning the min for
  43257. * @returns the depth min z
  43258. */
  43259. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43260. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43261. };
  43262. /**
  43263. * Gets the maxZ used for shadow according to both the scene and the light.
  43264. * @param activeCamera The camera we are returning the max for
  43265. * @returns the depth max z
  43266. */
  43267. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43268. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43269. };
  43270. /**
  43271. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43272. * @param matrix The materix to updated with the projection information
  43273. * @param viewMatrix The transform matrix of the light
  43274. * @param renderList The list of mesh to render in the map
  43275. * @returns The current light
  43276. */
  43277. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43278. if (this.customProjectionMatrixBuilder) {
  43279. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43280. }
  43281. else {
  43282. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43283. }
  43284. return this;
  43285. };
  43286. __decorate([
  43287. BABYLON.serializeAsVector3()
  43288. ], ShadowLight.prototype, "position", null);
  43289. __decorate([
  43290. BABYLON.serializeAsVector3()
  43291. ], ShadowLight.prototype, "direction", null);
  43292. __decorate([
  43293. BABYLON.serialize()
  43294. ], ShadowLight.prototype, "shadowMinZ", null);
  43295. __decorate([
  43296. BABYLON.serialize()
  43297. ], ShadowLight.prototype, "shadowMaxZ", null);
  43298. return ShadowLight;
  43299. }(BABYLON.Light));
  43300. BABYLON.ShadowLight = ShadowLight;
  43301. })(BABYLON || (BABYLON = {}));
  43302. //# sourceMappingURL=babylon.shadowLight.js.map
  43303. var BABYLON;
  43304. (function (BABYLON) {
  43305. /**
  43306. * A point light is a light defined by an unique point in world space.
  43307. * The light is emitted in every direction from this point.
  43308. * A good example of a point light is a standard light bulb.
  43309. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43310. */
  43311. var PointLight = /** @class */ (function (_super) {
  43312. __extends(PointLight, _super);
  43313. /**
  43314. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43315. * A PointLight emits the light in every direction.
  43316. * It can cast shadows.
  43317. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43318. * ```javascript
  43319. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43320. * ```
  43321. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43322. * @param name The light friendly name
  43323. * @param position The position of the point light in the scene
  43324. * @param scene The scene the lights belongs to
  43325. */
  43326. function PointLight(name, position, scene) {
  43327. var _this = _super.call(this, name, scene) || this;
  43328. _this._shadowAngle = Math.PI / 2;
  43329. _this.position = position;
  43330. return _this;
  43331. }
  43332. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43333. /**
  43334. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43335. * This specifies what angle the shadow will use to be created.
  43336. *
  43337. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43338. */
  43339. get: function () {
  43340. return this._shadowAngle;
  43341. },
  43342. /**
  43343. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43344. * This specifies what angle the shadow will use to be created.
  43345. *
  43346. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43347. */
  43348. set: function (value) {
  43349. this._shadowAngle = value;
  43350. this.forceProjectionMatrixCompute();
  43351. },
  43352. enumerable: true,
  43353. configurable: true
  43354. });
  43355. Object.defineProperty(PointLight.prototype, "direction", {
  43356. /**
  43357. * Gets the direction if it has been set.
  43358. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43359. */
  43360. get: function () {
  43361. return this._direction;
  43362. },
  43363. /**
  43364. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43365. */
  43366. set: function (value) {
  43367. var previousNeedCube = this.needCube();
  43368. this._direction = value;
  43369. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43370. this._shadowGenerator.recreateShadowMap();
  43371. }
  43372. },
  43373. enumerable: true,
  43374. configurable: true
  43375. });
  43376. /**
  43377. * Returns the string "PointLight"
  43378. * @returns the class name
  43379. */
  43380. PointLight.prototype.getClassName = function () {
  43381. return "PointLight";
  43382. };
  43383. /**
  43384. * Returns the integer 0.
  43385. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43386. */
  43387. PointLight.prototype.getTypeID = function () {
  43388. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43389. };
  43390. /**
  43391. * Specifies wether or not the shadowmap should be a cube texture.
  43392. * @returns true if the shadowmap needs to be a cube texture.
  43393. */
  43394. PointLight.prototype.needCube = function () {
  43395. return !this.direction;
  43396. };
  43397. /**
  43398. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43399. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43400. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43401. */
  43402. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43403. if (this.direction) {
  43404. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43405. }
  43406. else {
  43407. switch (faceIndex) {
  43408. case 0:
  43409. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43410. case 1:
  43411. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43412. case 2:
  43413. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43414. case 3:
  43415. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43416. case 4:
  43417. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43418. case 5:
  43419. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43420. }
  43421. }
  43422. return BABYLON.Vector3.Zero();
  43423. };
  43424. /**
  43425. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43426. * - fov = PI / 2
  43427. * - aspect ratio : 1.0
  43428. * - z-near and far equal to the active camera minZ and maxZ.
  43429. * Returns the PointLight.
  43430. */
  43431. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43432. var activeCamera = this.getScene().activeCamera;
  43433. if (!activeCamera) {
  43434. return;
  43435. }
  43436. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43437. };
  43438. PointLight.prototype._buildUniformLayout = function () {
  43439. this._uniformBuffer.addUniform("vLightData", 4);
  43440. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43441. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43442. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43443. this._uniformBuffer.addUniform("depthValues", 2);
  43444. this._uniformBuffer.create();
  43445. };
  43446. /**
  43447. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43448. * @param effect The effect to update
  43449. * @param lightIndex The index of the light in the effect to update
  43450. * @returns The point light
  43451. */
  43452. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43453. if (this.computeTransformedInformation()) {
  43454. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43455. return this;
  43456. }
  43457. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43458. return this;
  43459. };
  43460. __decorate([
  43461. BABYLON.serialize()
  43462. ], PointLight.prototype, "shadowAngle", null);
  43463. return PointLight;
  43464. }(BABYLON.ShadowLight));
  43465. BABYLON.PointLight = PointLight;
  43466. })(BABYLON || (BABYLON = {}));
  43467. //# sourceMappingURL=babylon.pointLight.js.map
  43468. var BABYLON;
  43469. (function (BABYLON) {
  43470. /**
  43471. * A directional light is defined by a direction (what a surprise!).
  43472. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43473. * 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.
  43474. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43475. */
  43476. var DirectionalLight = /** @class */ (function (_super) {
  43477. __extends(DirectionalLight, _super);
  43478. /**
  43479. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43480. * The directional light is emitted from everywhere in the given direction.
  43481. * It can cast shawdows.
  43482. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43483. * @param name The friendly name of the light
  43484. * @param direction The direction of the light
  43485. * @param scene The scene the light belongs to
  43486. */
  43487. function DirectionalLight(name, direction, scene) {
  43488. var _this = _super.call(this, name, scene) || this;
  43489. _this._shadowFrustumSize = 0;
  43490. _this._shadowOrthoScale = 0.5;
  43491. /**
  43492. * Automatically compute the projection matrix to best fit (including all the casters)
  43493. * on each frame.
  43494. */
  43495. _this.autoUpdateExtends = true;
  43496. // Cache
  43497. _this._orthoLeft = Number.MAX_VALUE;
  43498. _this._orthoRight = Number.MIN_VALUE;
  43499. _this._orthoTop = Number.MIN_VALUE;
  43500. _this._orthoBottom = Number.MAX_VALUE;
  43501. _this.position = direction.scale(-1.0);
  43502. _this.direction = direction;
  43503. return _this;
  43504. }
  43505. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43506. /**
  43507. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43508. */
  43509. get: function () {
  43510. return this._shadowFrustumSize;
  43511. },
  43512. /**
  43513. * Specifies a fix frustum size for the shadow generation.
  43514. */
  43515. set: function (value) {
  43516. this._shadowFrustumSize = value;
  43517. this.forceProjectionMatrixCompute();
  43518. },
  43519. enumerable: true,
  43520. configurable: true
  43521. });
  43522. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43523. /**
  43524. * Gets the shadow projection scale against the optimal computed one.
  43525. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43526. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43527. */
  43528. get: function () {
  43529. return this._shadowOrthoScale;
  43530. },
  43531. /**
  43532. * Sets the shadow projection scale against the optimal computed one.
  43533. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43534. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43535. */
  43536. set: function (value) {
  43537. this._shadowOrthoScale = value;
  43538. this.forceProjectionMatrixCompute();
  43539. },
  43540. enumerable: true,
  43541. configurable: true
  43542. });
  43543. /**
  43544. * Returns the string "DirectionalLight".
  43545. * @return The class name
  43546. */
  43547. DirectionalLight.prototype.getClassName = function () {
  43548. return "DirectionalLight";
  43549. };
  43550. /**
  43551. * Returns the integer 1.
  43552. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43553. */
  43554. DirectionalLight.prototype.getTypeID = function () {
  43555. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43556. };
  43557. /**
  43558. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43559. * Returns the DirectionalLight Shadow projection matrix.
  43560. */
  43561. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43562. if (this.shadowFrustumSize > 0) {
  43563. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43564. }
  43565. else {
  43566. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43567. }
  43568. };
  43569. /**
  43570. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43571. * Returns the DirectionalLight Shadow projection matrix.
  43572. */
  43573. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43574. var activeCamera = this.getScene().activeCamera;
  43575. if (!activeCamera) {
  43576. return;
  43577. }
  43578. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43579. };
  43580. /**
  43581. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43582. * Returns the DirectionalLight Shadow projection matrix.
  43583. */
  43584. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43585. var activeCamera = this.getScene().activeCamera;
  43586. if (!activeCamera) {
  43587. return;
  43588. }
  43589. // Check extends
  43590. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43591. var tempVector3 = BABYLON.Vector3.Zero();
  43592. this._orthoLeft = Number.MAX_VALUE;
  43593. this._orthoRight = Number.MIN_VALUE;
  43594. this._orthoTop = Number.MIN_VALUE;
  43595. this._orthoBottom = Number.MAX_VALUE;
  43596. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43597. var mesh = renderList[meshIndex];
  43598. if (!mesh) {
  43599. continue;
  43600. }
  43601. var boundingInfo = mesh.getBoundingInfo();
  43602. var boundingBox = boundingInfo.boundingBox;
  43603. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43604. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43605. if (tempVector3.x < this._orthoLeft)
  43606. this._orthoLeft = tempVector3.x;
  43607. if (tempVector3.y < this._orthoBottom)
  43608. this._orthoBottom = tempVector3.y;
  43609. if (tempVector3.x > this._orthoRight)
  43610. this._orthoRight = tempVector3.x;
  43611. if (tempVector3.y > this._orthoTop)
  43612. this._orthoTop = tempVector3.y;
  43613. }
  43614. }
  43615. }
  43616. var xOffset = this._orthoRight - this._orthoLeft;
  43617. var yOffset = this._orthoTop - this._orthoBottom;
  43618. 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);
  43619. };
  43620. DirectionalLight.prototype._buildUniformLayout = function () {
  43621. this._uniformBuffer.addUniform("vLightData", 4);
  43622. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43623. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43624. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43625. this._uniformBuffer.addUniform("depthValues", 2);
  43626. this._uniformBuffer.create();
  43627. };
  43628. /**
  43629. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43630. * @param effect The effect to update
  43631. * @param lightIndex The index of the light in the effect to update
  43632. * @returns The directional light
  43633. */
  43634. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43635. if (this.computeTransformedInformation()) {
  43636. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43637. return this;
  43638. }
  43639. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43640. return this;
  43641. };
  43642. /**
  43643. * Gets the minZ used for shadow according to both the scene and the light.
  43644. *
  43645. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43646. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43647. * @param activeCamera The camera we are returning the min for
  43648. * @returns the depth min z
  43649. */
  43650. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43651. return 1;
  43652. };
  43653. /**
  43654. * Gets the maxZ used for shadow according to both the scene and the light.
  43655. *
  43656. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43657. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43658. * @param activeCamera The camera we are returning the max for
  43659. * @returns the depth max z
  43660. */
  43661. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43662. return 1;
  43663. };
  43664. __decorate([
  43665. BABYLON.serialize()
  43666. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43667. __decorate([
  43668. BABYLON.serialize()
  43669. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43670. __decorate([
  43671. BABYLON.serialize()
  43672. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43673. return DirectionalLight;
  43674. }(BABYLON.ShadowLight));
  43675. BABYLON.DirectionalLight = DirectionalLight;
  43676. })(BABYLON || (BABYLON = {}));
  43677. //# sourceMappingURL=babylon.directionalLight.js.map
  43678. var BABYLON;
  43679. (function (BABYLON) {
  43680. /**
  43681. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43682. * These values define a cone of light starting from the position, emitting toward the direction.
  43683. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43684. * and the exponent defines the speed of the decay of the light with distance (reach).
  43685. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43686. */
  43687. var SpotLight = /** @class */ (function (_super) {
  43688. __extends(SpotLight, _super);
  43689. /**
  43690. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43691. * It can cast shadows.
  43692. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43693. * @param name The light friendly name
  43694. * @param position The position of the spot light in the scene
  43695. * @param direction The direction of the light in the scene
  43696. * @param angle The cone angle of the light in Radians
  43697. * @param exponent The light decay speed with the distance from the emission spot
  43698. * @param scene The scene the lights belongs to
  43699. */
  43700. function SpotLight(name, position, direction, angle, exponent, scene) {
  43701. var _this = _super.call(this, name, scene) || this;
  43702. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  43703. _this._projectionTextureLightNear = 1e-6;
  43704. _this._projectionTextureLightFar = 1000.0;
  43705. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  43706. _this._projectionTextureViewLightDirty = true;
  43707. _this._projectionTextureProjectionLightDirty = true;
  43708. _this._projectionTextureDirty = true;
  43709. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  43710. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  43711. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  43712. _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);
  43713. _this.position = position;
  43714. _this.direction = direction;
  43715. _this.angle = angle;
  43716. _this.exponent = exponent;
  43717. return _this;
  43718. }
  43719. Object.defineProperty(SpotLight.prototype, "angle", {
  43720. /**
  43721. * Gets the cone angle of the spot light in Radians.
  43722. */
  43723. get: function () {
  43724. return this._angle;
  43725. },
  43726. /**
  43727. * Sets the cone angle of the spot light in Radians.
  43728. */
  43729. set: function (value) {
  43730. this._angle = value;
  43731. this._projectionTextureProjectionLightDirty = true;
  43732. this.forceProjectionMatrixCompute();
  43733. },
  43734. enumerable: true,
  43735. configurable: true
  43736. });
  43737. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43738. /**
  43739. * Allows scaling the angle of the light for shadow generation only.
  43740. */
  43741. get: function () {
  43742. return this._shadowAngleScale;
  43743. },
  43744. /**
  43745. * Allows scaling the angle of the light for shadow generation only.
  43746. */
  43747. set: function (value) {
  43748. this._shadowAngleScale = value;
  43749. this.forceProjectionMatrixCompute();
  43750. },
  43751. enumerable: true,
  43752. configurable: true
  43753. });
  43754. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  43755. /**
  43756. * Allows reading the projecton texture
  43757. */
  43758. get: function () {
  43759. return this._projectionTextureMatrix;
  43760. },
  43761. enumerable: true,
  43762. configurable: true
  43763. });
  43764. ;
  43765. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  43766. /**
  43767. * Gets the near clip of the Spotlight for texture projection.
  43768. */
  43769. get: function () {
  43770. return this._projectionTextureLightNear;
  43771. },
  43772. /**
  43773. * Sets the near clip of the Spotlight for texture projection.
  43774. */
  43775. set: function (value) {
  43776. this._projectionTextureLightNear = value;
  43777. this._projectionTextureProjectionLightDirty = true;
  43778. },
  43779. enumerable: true,
  43780. configurable: true
  43781. });
  43782. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  43783. /**
  43784. * Gets the far clip of the Spotlight for texture projection.
  43785. */
  43786. get: function () {
  43787. return this._projectionTextureLightFar;
  43788. },
  43789. /**
  43790. * Sets the far clip of the Spotlight for texture projection.
  43791. */
  43792. set: function (value) {
  43793. this._projectionTextureLightFar = value;
  43794. this._projectionTextureProjectionLightDirty = true;
  43795. },
  43796. enumerable: true,
  43797. configurable: true
  43798. });
  43799. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  43800. /**
  43801. * Gets the Up vector of the Spotlight for texture projection.
  43802. */
  43803. get: function () {
  43804. return this._projectionTextureUpDirection;
  43805. },
  43806. /**
  43807. * Sets the Up vector of the Spotlight for texture projection.
  43808. */
  43809. set: function (value) {
  43810. this._projectionTextureUpDirection = value;
  43811. this._projectionTextureProjectionLightDirty = true;
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. ;
  43817. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  43818. /**
  43819. * Gets the projection texture of the light.
  43820. */
  43821. get: function () {
  43822. return this._projectionTexture;
  43823. },
  43824. /**
  43825. * Sets the projection texture of the light.
  43826. */
  43827. set: function (value) {
  43828. this._projectionTexture = value;
  43829. this._projectionTextureDirty = true;
  43830. },
  43831. enumerable: true,
  43832. configurable: true
  43833. });
  43834. /**
  43835. * Returns the string "SpotLight".
  43836. * @returns the class name
  43837. */
  43838. SpotLight.prototype.getClassName = function () {
  43839. return "SpotLight";
  43840. };
  43841. /**
  43842. * Returns the integer 2.
  43843. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43844. */
  43845. SpotLight.prototype.getTypeID = function () {
  43846. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43847. };
  43848. /**
  43849. * Overrides the direction setter to recompute the projection texture view light Matrix.
  43850. */
  43851. SpotLight.prototype._setDirection = function (value) {
  43852. _super.prototype._setDirection.call(this, value);
  43853. this._projectionTextureViewLightDirty = true;
  43854. };
  43855. /**
  43856. * Overrides the position setter to recompute the projection texture view light Matrix.
  43857. */
  43858. SpotLight.prototype._setPosition = function (value) {
  43859. _super.prototype._setPosition.call(this, value);
  43860. this._projectionTextureViewLightDirty = true;
  43861. };
  43862. /**
  43863. * 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.
  43864. * Returns the SpotLight.
  43865. */
  43866. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43867. var activeCamera = this.getScene().activeCamera;
  43868. if (!activeCamera) {
  43869. return;
  43870. }
  43871. this._shadowAngleScale = this._shadowAngleScale || 1;
  43872. var angle = this._shadowAngleScale * this._angle;
  43873. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43874. };
  43875. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  43876. this._projectionTextureViewLightDirty = false;
  43877. this._projectionTextureDirty = true;
  43878. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  43879. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  43880. };
  43881. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  43882. this._projectionTextureProjectionLightDirty = false;
  43883. this._projectionTextureDirty = true;
  43884. var light_far = this.projectionTextureLightFar;
  43885. var light_near = this.projectionTextureLightNear;
  43886. var P = light_far / (light_far - light_near);
  43887. var Q = -P * light_near;
  43888. var S = 1.0 / Math.tan(this._angle / 2.0);
  43889. var A = 1.0;
  43890. 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);
  43891. };
  43892. /**
  43893. * Main function for light texture projection matrix computing.
  43894. */
  43895. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  43896. this._projectionTextureDirty = false;
  43897. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  43898. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  43899. };
  43900. SpotLight.prototype._buildUniformLayout = function () {
  43901. this._uniformBuffer.addUniform("vLightData", 4);
  43902. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43903. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43904. this._uniformBuffer.addUniform("vLightDirection", 3);
  43905. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43906. this._uniformBuffer.addUniform("depthValues", 2);
  43907. this._uniformBuffer.create();
  43908. };
  43909. /**
  43910. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43911. * @param effect The effect to update
  43912. * @param lightIndex The index of the light in the effect to update
  43913. * @returns The spot light
  43914. */
  43915. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43916. var normalizeDirection;
  43917. if (this.computeTransformedInformation()) {
  43918. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43919. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43920. }
  43921. else {
  43922. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43923. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43924. }
  43925. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43926. if (this.projectionTexture && this.projectionTexture.isReady()) {
  43927. if (this._projectionTextureViewLightDirty) {
  43928. this._computeProjectionTextureViewLightMatrix();
  43929. }
  43930. if (this._projectionTextureProjectionLightDirty) {
  43931. this._computeProjectionTextureProjectionLightMatrix();
  43932. }
  43933. if (this._projectionTextureDirty) {
  43934. this._computeProjectionTextureMatrix();
  43935. }
  43936. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  43937. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  43938. }
  43939. return this;
  43940. };
  43941. /**
  43942. * Disposes the light and the associated resources.
  43943. */
  43944. SpotLight.prototype.dispose = function () {
  43945. _super.prototype.dispose.call(this);
  43946. if (this._projectionTexture) {
  43947. this._projectionTexture.dispose();
  43948. }
  43949. };
  43950. __decorate([
  43951. BABYLON.serialize()
  43952. ], SpotLight.prototype, "angle", null);
  43953. __decorate([
  43954. BABYLON.serialize()
  43955. ], SpotLight.prototype, "shadowAngleScale", null);
  43956. __decorate([
  43957. BABYLON.serialize()
  43958. ], SpotLight.prototype, "exponent", void 0);
  43959. __decorate([
  43960. BABYLON.serialize()
  43961. ], SpotLight.prototype, "projectionTextureLightNear", null);
  43962. __decorate([
  43963. BABYLON.serialize()
  43964. ], SpotLight.prototype, "projectionTextureLightFar", null);
  43965. __decorate([
  43966. BABYLON.serialize()
  43967. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  43968. __decorate([
  43969. BABYLON.serializeAsTexture("projectedLightTexture")
  43970. ], SpotLight.prototype, "_projectionTexture", void 0);
  43971. return SpotLight;
  43972. }(BABYLON.ShadowLight));
  43973. BABYLON.SpotLight = SpotLight;
  43974. })(BABYLON || (BABYLON = {}));
  43975. //# sourceMappingURL=babylon.spotLight.js.map
  43976. var BABYLON;
  43977. (function (BABYLON) {
  43978. var AnimationRange = /** @class */ (function () {
  43979. function AnimationRange(name, from, to) {
  43980. this.name = name;
  43981. this.from = from;
  43982. this.to = to;
  43983. }
  43984. AnimationRange.prototype.clone = function () {
  43985. return new AnimationRange(this.name, this.from, this.to);
  43986. };
  43987. return AnimationRange;
  43988. }());
  43989. BABYLON.AnimationRange = AnimationRange;
  43990. /**
  43991. * Composed of a frame, and an action function
  43992. */
  43993. var AnimationEvent = /** @class */ (function () {
  43994. function AnimationEvent(frame, action, onlyOnce) {
  43995. this.frame = frame;
  43996. this.action = action;
  43997. this.onlyOnce = onlyOnce;
  43998. this.isDone = false;
  43999. }
  44000. return AnimationEvent;
  44001. }());
  44002. BABYLON.AnimationEvent = AnimationEvent;
  44003. var PathCursor = /** @class */ (function () {
  44004. function PathCursor(path) {
  44005. this.path = path;
  44006. this._onchange = new Array();
  44007. this.value = 0;
  44008. this.animations = new Array();
  44009. }
  44010. PathCursor.prototype.getPoint = function () {
  44011. var point = this.path.getPointAtLengthPosition(this.value);
  44012. return new BABYLON.Vector3(point.x, 0, point.y);
  44013. };
  44014. PathCursor.prototype.moveAhead = function (step) {
  44015. if (step === void 0) { step = 0.002; }
  44016. this.move(step);
  44017. return this;
  44018. };
  44019. PathCursor.prototype.moveBack = function (step) {
  44020. if (step === void 0) { step = 0.002; }
  44021. this.move(-step);
  44022. return this;
  44023. };
  44024. PathCursor.prototype.move = function (step) {
  44025. if (Math.abs(step) > 1) {
  44026. throw "step size should be less than 1.";
  44027. }
  44028. this.value += step;
  44029. this.ensureLimits();
  44030. this.raiseOnChange();
  44031. return this;
  44032. };
  44033. PathCursor.prototype.ensureLimits = function () {
  44034. while (this.value > 1) {
  44035. this.value -= 1;
  44036. }
  44037. while (this.value < 0) {
  44038. this.value += 1;
  44039. }
  44040. return this;
  44041. };
  44042. // used by animation engine
  44043. PathCursor.prototype.raiseOnChange = function () {
  44044. var _this = this;
  44045. this._onchange.forEach(function (f) { return f(_this); });
  44046. return this;
  44047. };
  44048. PathCursor.prototype.onchange = function (f) {
  44049. this._onchange.push(f);
  44050. return this;
  44051. };
  44052. return PathCursor;
  44053. }());
  44054. BABYLON.PathCursor = PathCursor;
  44055. var AnimationKeyInterpolation;
  44056. (function (AnimationKeyInterpolation) {
  44057. /**
  44058. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  44059. */
  44060. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  44061. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  44062. var Animation = /** @class */ (function () {
  44063. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  44064. this.name = name;
  44065. this.targetProperty = targetProperty;
  44066. this.framePerSecond = framePerSecond;
  44067. this.dataType = dataType;
  44068. this.loopMode = loopMode;
  44069. this.enableBlending = enableBlending;
  44070. this._runtimeAnimations = new Array();
  44071. // The set of event that will be linked to this animation
  44072. this._events = new Array();
  44073. this.blendingSpeed = 0.01;
  44074. this._ranges = {};
  44075. this.targetPropertyPath = targetProperty.split(".");
  44076. this.dataType = dataType;
  44077. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  44078. }
  44079. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  44080. var dataType = undefined;
  44081. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  44082. dataType = Animation.ANIMATIONTYPE_FLOAT;
  44083. }
  44084. else if (from instanceof BABYLON.Quaternion) {
  44085. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  44086. }
  44087. else if (from instanceof BABYLON.Vector3) {
  44088. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  44089. }
  44090. else if (from instanceof BABYLON.Vector2) {
  44091. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  44092. }
  44093. else if (from instanceof BABYLON.Color3) {
  44094. dataType = Animation.ANIMATIONTYPE_COLOR3;
  44095. }
  44096. else if (from instanceof BABYLON.Size) {
  44097. dataType = Animation.ANIMATIONTYPE_SIZE;
  44098. }
  44099. if (dataType == undefined) {
  44100. return null;
  44101. }
  44102. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  44103. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  44104. animation.setKeys(keys);
  44105. if (easingFunction !== undefined) {
  44106. animation.setEasingFunction(easingFunction);
  44107. }
  44108. return animation;
  44109. };
  44110. /**
  44111. * Sets up an animation.
  44112. * @param property the property to animate
  44113. * @param animationType the animation type to apply
  44114. * @param easingFunction the easing function used in the animation
  44115. * @returns The created animation
  44116. */
  44117. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  44118. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  44119. animation.setEasingFunction(easingFunction);
  44120. return animation;
  44121. };
  44122. /**
  44123. * Create and start an animation on a node
  44124. * @param {string} name defines the name of the global animation that will be run on all nodes
  44125. * @param {BABYLON.Node} node defines the root node where the animation will take place
  44126. * @param {string} targetProperty defines property to animate
  44127. * @param {number} framePerSecond defines the number of frame per second yo use
  44128. * @param {number} totalFrame defines the number of frames in total
  44129. * @param {any} from defines the initial value
  44130. * @param {any} to defines the final value
  44131. * @param {number} loopMode defines which loop mode you want to use (off by default)
  44132. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  44133. * @param onAnimationEnd defines the callback to call when animation end
  44134. * @returns the animatable created for this animation
  44135. */
  44136. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44137. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44138. if (!animation) {
  44139. return null;
  44140. }
  44141. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44142. };
  44143. /**
  44144. * Create and start an animation on a node and its descendants
  44145. * @param {string} name defines the name of the global animation that will be run on all nodes
  44146. * @param {BABYLON.Node} node defines the root node where the animation will take place
  44147. * @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.
  44148. * @param {string} targetProperty defines property to animate
  44149. * @param {number} framePerSecond defines the number of frame per second yo use
  44150. * @param {number} totalFrame defines the number of frames in total
  44151. * @param {any} from defines the initial value
  44152. * @param {any} to defines the final value
  44153. * @param {number} loopMode defines which loop mode you want to use (off by default)
  44154. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  44155. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  44156. * @returns the list of animatables created for all nodes
  44157. * @example https://www.babylonjs-playground.com/#MH0VLI
  44158. */
  44159. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44160. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44161. if (!animation) {
  44162. return null;
  44163. }
  44164. var scene = node.getScene();
  44165. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44166. };
  44167. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44168. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44169. if (!animation) {
  44170. return null;
  44171. }
  44172. node.animations.push(animation);
  44173. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44174. };
  44175. /**
  44176. * Transition property of the Camera to the target Value.
  44177. * @param property The property to transition
  44178. * @param targetValue The target Value of the property
  44179. * @param host The object where the property to animate belongs
  44180. * @param scene Scene used to run the animation
  44181. * @param frameRate Framerate (in frame/s) to use
  44182. * @param transition The transition type we want to use
  44183. * @param duration The duration of the animation, in milliseconds
  44184. * @param onAnimationEnd Call back trigger at the end of the animation.
  44185. */
  44186. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  44187. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  44188. if (duration <= 0) {
  44189. host[property] = targetValue;
  44190. if (onAnimationEnd) {
  44191. onAnimationEnd();
  44192. }
  44193. return null;
  44194. }
  44195. var endFrame = frameRate * (duration / 1000);
  44196. transition.setKeys([{
  44197. frame: 0,
  44198. value: host[property].clone ? host[property].clone() : host[property]
  44199. },
  44200. {
  44201. frame: endFrame,
  44202. value: targetValue
  44203. }]);
  44204. if (!host.animations) {
  44205. host.animations = [];
  44206. }
  44207. host.animations.push(transition);
  44208. var animation = scene.beginAnimation(host, 0, endFrame, false);
  44209. animation.onAnimationEnd = onAnimationEnd;
  44210. return animation;
  44211. };
  44212. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  44213. /**
  44214. * Return the array of runtime animations currently using this animation
  44215. */
  44216. get: function () {
  44217. return this._runtimeAnimations;
  44218. },
  44219. enumerable: true,
  44220. configurable: true
  44221. });
  44222. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  44223. get: function () {
  44224. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  44225. var runtimeAnimation = _a[_i];
  44226. if (!runtimeAnimation.isStopped) {
  44227. return true;
  44228. }
  44229. }
  44230. return false;
  44231. },
  44232. enumerable: true,
  44233. configurable: true
  44234. });
  44235. // Methods
  44236. /**
  44237. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  44238. */
  44239. Animation.prototype.toString = function (fullDetails) {
  44240. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  44241. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  44242. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  44243. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  44244. if (fullDetails) {
  44245. ret += ", Ranges: {";
  44246. var first = true;
  44247. for (var name in this._ranges) {
  44248. if (first) {
  44249. ret += ", ";
  44250. first = false;
  44251. }
  44252. ret += name;
  44253. }
  44254. ret += "}";
  44255. }
  44256. return ret;
  44257. };
  44258. /**
  44259. * Add an event to this animation.
  44260. */
  44261. Animation.prototype.addEvent = function (event) {
  44262. this._events.push(event);
  44263. };
  44264. /**
  44265. * Remove all events found at the given frame
  44266. * @param frame
  44267. */
  44268. Animation.prototype.removeEvents = function (frame) {
  44269. for (var index = 0; index < this._events.length; index++) {
  44270. if (this._events[index].frame === frame) {
  44271. this._events.splice(index, 1);
  44272. index--;
  44273. }
  44274. }
  44275. };
  44276. Animation.prototype.getEvents = function () {
  44277. return this._events;
  44278. };
  44279. Animation.prototype.createRange = function (name, from, to) {
  44280. // check name not already in use; could happen for bones after serialized
  44281. if (!this._ranges[name]) {
  44282. this._ranges[name] = new AnimationRange(name, from, to);
  44283. }
  44284. };
  44285. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44286. if (deleteFrames === void 0) { deleteFrames = true; }
  44287. var range = this._ranges[name];
  44288. if (!range) {
  44289. return;
  44290. }
  44291. if (deleteFrames) {
  44292. var from = range.from;
  44293. var to = range.to;
  44294. // this loop MUST go high to low for multiple splices to work
  44295. for (var key = this._keys.length - 1; key >= 0; key--) {
  44296. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44297. this._keys.splice(key, 1);
  44298. }
  44299. }
  44300. }
  44301. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44302. };
  44303. Animation.prototype.getRange = function (name) {
  44304. return this._ranges[name];
  44305. };
  44306. Animation.prototype.getKeys = function () {
  44307. return this._keys;
  44308. };
  44309. Animation.prototype.getHighestFrame = function () {
  44310. var ret = 0;
  44311. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44312. if (ret < this._keys[key].frame) {
  44313. ret = this._keys[key].frame;
  44314. }
  44315. }
  44316. return ret;
  44317. };
  44318. Animation.prototype.getEasingFunction = function () {
  44319. return this._easingFunction;
  44320. };
  44321. Animation.prototype.setEasingFunction = function (easingFunction) {
  44322. this._easingFunction = easingFunction;
  44323. };
  44324. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44325. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44326. };
  44327. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44328. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44329. };
  44330. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44331. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44332. };
  44333. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44334. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44335. };
  44336. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44337. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44338. };
  44339. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44340. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44341. };
  44342. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44343. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44344. };
  44345. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44346. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44347. };
  44348. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44349. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44350. };
  44351. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44352. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44353. };
  44354. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44355. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44356. };
  44357. Animation.prototype.clone = function () {
  44358. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44359. clone.enableBlending = this.enableBlending;
  44360. clone.blendingSpeed = this.blendingSpeed;
  44361. if (this._keys) {
  44362. clone.setKeys(this._keys);
  44363. }
  44364. if (this._ranges) {
  44365. clone._ranges = {};
  44366. for (var name in this._ranges) {
  44367. var range = this._ranges[name];
  44368. if (!range) {
  44369. continue;
  44370. }
  44371. clone._ranges[name] = range.clone();
  44372. }
  44373. }
  44374. return clone;
  44375. };
  44376. Animation.prototype.setKeys = function (values) {
  44377. this._keys = values.slice(0);
  44378. };
  44379. Animation.prototype.serialize = function () {
  44380. var serializationObject = {};
  44381. serializationObject.name = this.name;
  44382. serializationObject.property = this.targetProperty;
  44383. serializationObject.framePerSecond = this.framePerSecond;
  44384. serializationObject.dataType = this.dataType;
  44385. serializationObject.loopBehavior = this.loopMode;
  44386. serializationObject.enableBlending = this.enableBlending;
  44387. serializationObject.blendingSpeed = this.blendingSpeed;
  44388. var dataType = this.dataType;
  44389. serializationObject.keys = [];
  44390. var keys = this.getKeys();
  44391. for (var index = 0; index < keys.length; index++) {
  44392. var animationKey = keys[index];
  44393. var key = {};
  44394. key.frame = animationKey.frame;
  44395. switch (dataType) {
  44396. case Animation.ANIMATIONTYPE_FLOAT:
  44397. key.values = [animationKey.value];
  44398. break;
  44399. case Animation.ANIMATIONTYPE_QUATERNION:
  44400. case Animation.ANIMATIONTYPE_MATRIX:
  44401. case Animation.ANIMATIONTYPE_VECTOR3:
  44402. case Animation.ANIMATIONTYPE_COLOR3:
  44403. key.values = animationKey.value.asArray();
  44404. break;
  44405. }
  44406. serializationObject.keys.push(key);
  44407. }
  44408. serializationObject.ranges = [];
  44409. for (var name in this._ranges) {
  44410. var source = this._ranges[name];
  44411. if (!source) {
  44412. continue;
  44413. }
  44414. var range = {};
  44415. range.name = name;
  44416. range.from = source.from;
  44417. range.to = source.to;
  44418. serializationObject.ranges.push(range);
  44419. }
  44420. return serializationObject;
  44421. };
  44422. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44423. get: function () {
  44424. return Animation._ANIMATIONTYPE_FLOAT;
  44425. },
  44426. enumerable: true,
  44427. configurable: true
  44428. });
  44429. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44430. get: function () {
  44431. return Animation._ANIMATIONTYPE_VECTOR3;
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44437. get: function () {
  44438. return Animation._ANIMATIONTYPE_VECTOR2;
  44439. },
  44440. enumerable: true,
  44441. configurable: true
  44442. });
  44443. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44444. get: function () {
  44445. return Animation._ANIMATIONTYPE_SIZE;
  44446. },
  44447. enumerable: true,
  44448. configurable: true
  44449. });
  44450. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44451. get: function () {
  44452. return Animation._ANIMATIONTYPE_QUATERNION;
  44453. },
  44454. enumerable: true,
  44455. configurable: true
  44456. });
  44457. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44458. get: function () {
  44459. return Animation._ANIMATIONTYPE_MATRIX;
  44460. },
  44461. enumerable: true,
  44462. configurable: true
  44463. });
  44464. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44465. get: function () {
  44466. return Animation._ANIMATIONTYPE_COLOR3;
  44467. },
  44468. enumerable: true,
  44469. configurable: true
  44470. });
  44471. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44472. get: function () {
  44473. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44474. },
  44475. enumerable: true,
  44476. configurable: true
  44477. });
  44478. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44479. get: function () {
  44480. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44481. },
  44482. enumerable: true,
  44483. configurable: true
  44484. });
  44485. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44486. get: function () {
  44487. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44488. },
  44489. enumerable: true,
  44490. configurable: true
  44491. });
  44492. Animation.Parse = function (parsedAnimation) {
  44493. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44494. var dataType = parsedAnimation.dataType;
  44495. var keys = [];
  44496. var data;
  44497. var index;
  44498. if (parsedAnimation.enableBlending) {
  44499. animation.enableBlending = parsedAnimation.enableBlending;
  44500. }
  44501. if (parsedAnimation.blendingSpeed) {
  44502. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44503. }
  44504. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44505. var key = parsedAnimation.keys[index];
  44506. var inTangent;
  44507. var outTangent;
  44508. switch (dataType) {
  44509. case Animation.ANIMATIONTYPE_FLOAT:
  44510. data = key.values[0];
  44511. if (key.values.length >= 1) {
  44512. inTangent = key.values[1];
  44513. }
  44514. if (key.values.length >= 2) {
  44515. outTangent = key.values[2];
  44516. }
  44517. break;
  44518. case Animation.ANIMATIONTYPE_QUATERNION:
  44519. data = BABYLON.Quaternion.FromArray(key.values);
  44520. if (key.values.length >= 8) {
  44521. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44522. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44523. inTangent = _inTangent;
  44524. }
  44525. }
  44526. if (key.values.length >= 12) {
  44527. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44528. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44529. outTangent = _outTangent;
  44530. }
  44531. }
  44532. break;
  44533. case Animation.ANIMATIONTYPE_MATRIX:
  44534. data = BABYLON.Matrix.FromArray(key.values);
  44535. break;
  44536. case Animation.ANIMATIONTYPE_COLOR3:
  44537. data = BABYLON.Color3.FromArray(key.values);
  44538. break;
  44539. case Animation.ANIMATIONTYPE_VECTOR3:
  44540. default:
  44541. data = BABYLON.Vector3.FromArray(key.values);
  44542. break;
  44543. }
  44544. var keyData = {};
  44545. keyData.frame = key.frame;
  44546. keyData.value = data;
  44547. if (inTangent != undefined) {
  44548. keyData.inTangent = inTangent;
  44549. }
  44550. if (outTangent != undefined) {
  44551. keyData.outTangent = outTangent;
  44552. }
  44553. keys.push(keyData);
  44554. }
  44555. animation.setKeys(keys);
  44556. if (parsedAnimation.ranges) {
  44557. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44558. data = parsedAnimation.ranges[index];
  44559. animation.createRange(data.name, data.from, data.to);
  44560. }
  44561. }
  44562. return animation;
  44563. };
  44564. Animation.AppendSerializedAnimations = function (source, destination) {
  44565. if (source.animations) {
  44566. destination.animations = [];
  44567. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44568. var animation = source.animations[animationIndex];
  44569. destination.animations.push(animation.serialize());
  44570. }
  44571. }
  44572. };
  44573. Animation.AllowMatricesInterpolation = false;
  44574. // Statics
  44575. Animation._ANIMATIONTYPE_FLOAT = 0;
  44576. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44577. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44578. Animation._ANIMATIONTYPE_MATRIX = 3;
  44579. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44580. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44581. Animation._ANIMATIONTYPE_SIZE = 6;
  44582. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44583. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44584. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44585. return Animation;
  44586. }());
  44587. BABYLON.Animation = Animation;
  44588. })(BABYLON || (BABYLON = {}));
  44589. //# sourceMappingURL=babylon.animation.js.map
  44590. var BABYLON;
  44591. (function (BABYLON) {
  44592. /**
  44593. * This class defines the direct association between an animation and a target
  44594. */
  44595. var TargetedAnimation = /** @class */ (function () {
  44596. function TargetedAnimation() {
  44597. }
  44598. return TargetedAnimation;
  44599. }());
  44600. BABYLON.TargetedAnimation = TargetedAnimation;
  44601. /**
  44602. * Use this class to create coordinated animations on multiple targets
  44603. */
  44604. var AnimationGroup = /** @class */ (function () {
  44605. function AnimationGroup(name, scene) {
  44606. if (scene === void 0) { scene = null; }
  44607. this.name = name;
  44608. this._targetedAnimations = new Array();
  44609. this._animatables = new Array();
  44610. this._from = Number.MAX_VALUE;
  44611. this._to = -Number.MAX_VALUE;
  44612. this._speedRatio = 1;
  44613. this.onAnimationEndObservable = new BABYLON.Observable();
  44614. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44615. this._scene.animationGroups.push(this);
  44616. }
  44617. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44618. /**
  44619. * Define if the animations are started
  44620. */
  44621. get: function () {
  44622. return this._isStarted;
  44623. },
  44624. enumerable: true,
  44625. configurable: true
  44626. });
  44627. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44628. /**
  44629. * Gets or sets the speed ratio to use for all animations
  44630. */
  44631. get: function () {
  44632. return this._speedRatio;
  44633. },
  44634. /**
  44635. * Gets or sets the speed ratio to use for all animations
  44636. */
  44637. set: function (value) {
  44638. if (this._speedRatio === value) {
  44639. return;
  44640. }
  44641. this._speedRatio = value;
  44642. for (var index = 0; index < this._animatables.length; index++) {
  44643. var animatable = this._animatables[index];
  44644. animatable.speedRatio = this._speedRatio;
  44645. }
  44646. },
  44647. enumerable: true,
  44648. configurable: true
  44649. });
  44650. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44651. /**
  44652. * Gets the targeted animations for this animation group
  44653. */
  44654. get: function () {
  44655. return this._targetedAnimations;
  44656. },
  44657. enumerable: true,
  44658. configurable: true
  44659. });
  44660. /**
  44661. * Add an animation (with its target) in the group
  44662. * @param animation defines the animation we want to add
  44663. * @param target defines the target of the animation
  44664. * @returns the {BABYLON.TargetedAnimation} object
  44665. */
  44666. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44667. var targetedAnimation = {
  44668. animation: animation,
  44669. target: target
  44670. };
  44671. var keys = animation.getKeys();
  44672. if (this._from > keys[0].frame) {
  44673. this._from = keys[0].frame;
  44674. }
  44675. if (this._to < keys[keys.length - 1].frame) {
  44676. this._to = keys[keys.length - 1].frame;
  44677. }
  44678. this._targetedAnimations.push(targetedAnimation);
  44679. return targetedAnimation;
  44680. };
  44681. /**
  44682. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44683. * It can add constant keys at begin or end
  44684. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44685. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44686. */
  44687. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44688. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44689. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44690. beginFrame = Math.max(beginFrame, this._from);
  44691. endFrame = Math.min(endFrame, this._to);
  44692. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44693. var targetedAnimation = this._targetedAnimations[index];
  44694. var keys = targetedAnimation.animation.getKeys();
  44695. var startKey = keys[0];
  44696. var endKey = keys[keys.length - 1];
  44697. if (startKey.frame > beginFrame) {
  44698. var newKey = {
  44699. frame: beginFrame,
  44700. value: startKey.value,
  44701. inTangent: startKey.inTangent,
  44702. outTangent: startKey.outTangent,
  44703. interpolation: startKey.interpolation
  44704. };
  44705. keys.splice(0, 0, newKey);
  44706. }
  44707. if (endKey.frame < endFrame) {
  44708. var newKey = {
  44709. frame: endFrame,
  44710. value: endKey.value,
  44711. inTangent: endKey.outTangent,
  44712. outTangent: endKey.outTangent,
  44713. interpolation: endKey.interpolation
  44714. };
  44715. keys.push(newKey);
  44716. }
  44717. }
  44718. return this;
  44719. };
  44720. /**
  44721. * Start all animations on given targets
  44722. * @param loop defines if animations must loop
  44723. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44724. */
  44725. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44726. var _this = this;
  44727. if (loop === void 0) { loop = false; }
  44728. if (speedRatio === void 0) { speedRatio = 1; }
  44729. if (this._isStarted || this._targetedAnimations.length === 0) {
  44730. return this;
  44731. }
  44732. var _loop_1 = function () {
  44733. var targetedAnimation = this_1._targetedAnimations[index];
  44734. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44735. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44736. }));
  44737. };
  44738. var this_1 = this;
  44739. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44740. _loop_1();
  44741. }
  44742. this._speedRatio = speedRatio;
  44743. this._isStarted = true;
  44744. return this;
  44745. };
  44746. /**
  44747. * Pause all animations
  44748. */
  44749. AnimationGroup.prototype.pause = function () {
  44750. if (!this._isStarted) {
  44751. return this;
  44752. }
  44753. for (var index = 0; index < this._animatables.length; index++) {
  44754. var animatable = this._animatables[index];
  44755. animatable.pause();
  44756. }
  44757. return this;
  44758. };
  44759. /**
  44760. * Play all animations to initial state
  44761. * This function will start() the animations if they were not started or will restart() them if they were paused
  44762. * @param loop defines if animations must loop
  44763. */
  44764. AnimationGroup.prototype.play = function (loop) {
  44765. if (this.isStarted) {
  44766. if (loop !== undefined) {
  44767. for (var index = 0; index < this._animatables.length; index++) {
  44768. var animatable = this._animatables[index];
  44769. animatable.loopAnimation = loop;
  44770. }
  44771. }
  44772. this.restart();
  44773. }
  44774. else {
  44775. this.start(loop, this._speedRatio);
  44776. }
  44777. return this;
  44778. };
  44779. /**
  44780. * Reset all animations to initial state
  44781. */
  44782. AnimationGroup.prototype.reset = function () {
  44783. if (!this._isStarted) {
  44784. return this;
  44785. }
  44786. for (var index = 0; index < this._animatables.length; index++) {
  44787. var animatable = this._animatables[index];
  44788. animatable.reset();
  44789. }
  44790. return this;
  44791. };
  44792. /**
  44793. * Restart animations from key 0
  44794. */
  44795. AnimationGroup.prototype.restart = function () {
  44796. if (!this._isStarted) {
  44797. return this;
  44798. }
  44799. for (var index = 0; index < this._animatables.length; index++) {
  44800. var animatable = this._animatables[index];
  44801. animatable.restart();
  44802. }
  44803. return this;
  44804. };
  44805. /**
  44806. * Stop all animations
  44807. */
  44808. AnimationGroup.prototype.stop = function () {
  44809. if (!this._isStarted) {
  44810. return this;
  44811. }
  44812. for (var index = 0; index < this._animatables.length; index++) {
  44813. var animatable = this._animatables[index];
  44814. animatable.stop();
  44815. }
  44816. this._isStarted = false;
  44817. return this;
  44818. };
  44819. /**
  44820. * Dispose all associated resources
  44821. */
  44822. AnimationGroup.prototype.dispose = function () {
  44823. this._targetedAnimations = [];
  44824. this._animatables = [];
  44825. var index = this._scene.animationGroups.indexOf(this);
  44826. if (index > -1) {
  44827. this._scene.animationGroups.splice(index, 1);
  44828. }
  44829. };
  44830. return AnimationGroup;
  44831. }());
  44832. BABYLON.AnimationGroup = AnimationGroup;
  44833. })(BABYLON || (BABYLON = {}));
  44834. //# sourceMappingURL=babylon.animationGroup.js.map
  44835. var BABYLON;
  44836. (function (BABYLON) {
  44837. var RuntimeAnimation = /** @class */ (function () {
  44838. function RuntimeAnimation(target, animation) {
  44839. this._offsetsCache = {};
  44840. this._highLimitsCache = {};
  44841. this._stopped = false;
  44842. this._blendingFactor = 0;
  44843. this._ratioOffset = 0;
  44844. this._animation = animation;
  44845. this._target = target;
  44846. animation._runtimeAnimations.push(this);
  44847. }
  44848. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44849. get: function () {
  44850. return this._animation;
  44851. },
  44852. enumerable: true,
  44853. configurable: true
  44854. });
  44855. RuntimeAnimation.prototype.reset = function () {
  44856. this._offsetsCache = {};
  44857. this._highLimitsCache = {};
  44858. this.currentFrame = 0;
  44859. this._blendingFactor = 0;
  44860. this._originalBlendValue = null;
  44861. };
  44862. RuntimeAnimation.prototype.isStopped = function () {
  44863. return this._stopped;
  44864. };
  44865. RuntimeAnimation.prototype.dispose = function () {
  44866. var index = this._animation.runtimeAnimations.indexOf(this);
  44867. if (index > -1) {
  44868. this._animation.runtimeAnimations.splice(index, 1);
  44869. }
  44870. };
  44871. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44872. if (typeof value === "function") {
  44873. return value();
  44874. }
  44875. return value;
  44876. };
  44877. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44878. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44879. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44880. }
  44881. this.currentFrame = currentFrame;
  44882. var keys = this._animation.getKeys();
  44883. // Try to get a hash to find the right key
  44884. 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));
  44885. if (keys[startKeyIndex].frame >= currentFrame) {
  44886. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44887. startKeyIndex--;
  44888. }
  44889. }
  44890. for (var key = startKeyIndex; key < keys.length; key++) {
  44891. var endKey = keys[key + 1];
  44892. if (endKey.frame >= currentFrame) {
  44893. var startKey = keys[key];
  44894. var startValue = this._getKeyValue(startKey.value);
  44895. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44896. return startValue;
  44897. }
  44898. var endValue = this._getKeyValue(endKey.value);
  44899. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44900. var frameDelta = endKey.frame - startKey.frame;
  44901. // gradient : percent of currentFrame between the frame inf and the frame sup
  44902. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44903. // check for easingFunction and correction of gradient
  44904. var easingFunction = this._animation.getEasingFunction();
  44905. if (easingFunction != null) {
  44906. gradient = easingFunction.ease(gradient);
  44907. }
  44908. switch (this._animation.dataType) {
  44909. // Float
  44910. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44911. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44912. switch (loopMode) {
  44913. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44914. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44915. return floatValue;
  44916. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44917. return offsetValue * repeatCount + floatValue;
  44918. }
  44919. break;
  44920. // Quaternion
  44921. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44922. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44923. switch (loopMode) {
  44924. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44925. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44926. return quatValue;
  44927. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44928. return quatValue.add(offsetValue.scale(repeatCount));
  44929. }
  44930. return quatValue;
  44931. // Vector3
  44932. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44933. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44934. switch (loopMode) {
  44935. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44936. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44937. return vec3Value;
  44938. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44939. return vec3Value.add(offsetValue.scale(repeatCount));
  44940. }
  44941. // Vector2
  44942. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44943. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44944. switch (loopMode) {
  44945. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44946. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44947. return vec2Value;
  44948. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44949. return vec2Value.add(offsetValue.scale(repeatCount));
  44950. }
  44951. // Size
  44952. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44953. switch (loopMode) {
  44954. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44955. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44956. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44957. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44958. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44959. }
  44960. // Color3
  44961. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44962. switch (loopMode) {
  44963. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44964. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44965. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44966. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44967. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44968. }
  44969. // Matrix
  44970. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44971. switch (loopMode) {
  44972. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44973. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44974. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44975. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44976. }
  44977. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44978. return startValue;
  44979. }
  44980. default:
  44981. break;
  44982. }
  44983. break;
  44984. }
  44985. }
  44986. return this._getKeyValue(keys[keys.length - 1].value);
  44987. };
  44988. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44989. if (blend === void 0) { blend = false; }
  44990. // Set value
  44991. var path;
  44992. var destination;
  44993. var targetPropertyPath = this._animation.targetPropertyPath;
  44994. if (targetPropertyPath.length > 1) {
  44995. var property = this._target[targetPropertyPath[0]];
  44996. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44997. property = property[targetPropertyPath[index]];
  44998. }
  44999. path = targetPropertyPath[targetPropertyPath.length - 1];
  45000. destination = property;
  45001. }
  45002. else {
  45003. path = targetPropertyPath[0];
  45004. destination = this._target;
  45005. }
  45006. // Blending
  45007. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  45008. if (!this._originalBlendValue) {
  45009. if (destination[path].clone) {
  45010. this._originalBlendValue = destination[path].clone();
  45011. }
  45012. else {
  45013. this._originalBlendValue = destination[path];
  45014. }
  45015. }
  45016. if (this._originalBlendValue.prototype) {
  45017. if (this._originalBlendValue.prototype.Lerp) {
  45018. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  45019. }
  45020. else {
  45021. destination[path] = currentValue;
  45022. }
  45023. }
  45024. else if (this._originalBlendValue.m) {
  45025. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  45026. }
  45027. else {
  45028. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  45029. }
  45030. this._blendingFactor += this._animation.blendingSpeed;
  45031. }
  45032. else {
  45033. destination[path] = currentValue;
  45034. }
  45035. if (this._target.markAsDirty) {
  45036. this._target.markAsDirty(this._animation.targetProperty);
  45037. }
  45038. };
  45039. RuntimeAnimation.prototype.goToFrame = function (frame) {
  45040. var keys = this._animation.getKeys();
  45041. if (frame < keys[0].frame) {
  45042. frame = keys[0].frame;
  45043. }
  45044. else if (frame > keys[keys.length - 1].frame) {
  45045. frame = keys[keys.length - 1].frame;
  45046. }
  45047. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  45048. this.setValue(currentValue);
  45049. };
  45050. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  45051. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  45052. this._ratioOffset = this._previousRatio - newRatio;
  45053. };
  45054. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  45055. if (blend === void 0) { blend = false; }
  45056. var targetPropertyPath = this._animation.targetPropertyPath;
  45057. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  45058. this._stopped = true;
  45059. return false;
  45060. }
  45061. var returnValue = true;
  45062. var keys = this._animation.getKeys();
  45063. // Adding a start key at frame 0 if missing
  45064. if (keys[0].frame !== 0) {
  45065. var newKey = { frame: 0, value: keys[0].value };
  45066. keys.splice(0, 0, newKey);
  45067. }
  45068. // Check limits
  45069. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  45070. from = keys[0].frame;
  45071. }
  45072. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  45073. to = keys[keys.length - 1].frame;
  45074. }
  45075. //to and from cannot be the same key
  45076. if (from === to) {
  45077. if (from > keys[0].frame) {
  45078. from--;
  45079. }
  45080. else if (to < keys[keys.length - 1].frame) {
  45081. to++;
  45082. }
  45083. }
  45084. // Compute ratio
  45085. var range = to - from;
  45086. var offsetValue;
  45087. // ratio represents the frame delta between from and to
  45088. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  45089. var highLimitValue = 0;
  45090. this._previousDelay = delay;
  45091. this._previousRatio = ratio;
  45092. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  45093. returnValue = false;
  45094. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  45095. }
  45096. else {
  45097. // Get max value if required
  45098. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  45099. var keyOffset = to.toString() + from.toString();
  45100. if (!this._offsetsCache[keyOffset]) {
  45101. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  45102. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  45103. switch (this._animation.dataType) {
  45104. // Float
  45105. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  45106. this._offsetsCache[keyOffset] = toValue - fromValue;
  45107. break;
  45108. // Quaternion
  45109. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  45110. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45111. break;
  45112. // Vector3
  45113. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  45114. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45115. // Vector2
  45116. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  45117. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45118. // Size
  45119. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  45120. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45121. // Color3
  45122. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  45123. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45124. default:
  45125. break;
  45126. }
  45127. this._highLimitsCache[keyOffset] = toValue;
  45128. }
  45129. highLimitValue = this._highLimitsCache[keyOffset];
  45130. offsetValue = this._offsetsCache[keyOffset];
  45131. }
  45132. }
  45133. if (offsetValue === undefined) {
  45134. switch (this._animation.dataType) {
  45135. // Float
  45136. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  45137. offsetValue = 0;
  45138. break;
  45139. // Quaternion
  45140. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  45141. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  45142. break;
  45143. // Vector3
  45144. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  45145. offsetValue = BABYLON.Vector3.Zero();
  45146. break;
  45147. // Vector2
  45148. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  45149. offsetValue = BABYLON.Vector2.Zero();
  45150. break;
  45151. // Size
  45152. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  45153. offsetValue = BABYLON.Size.Zero();
  45154. break;
  45155. // Color3
  45156. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  45157. offsetValue = BABYLON.Color3.Black();
  45158. }
  45159. }
  45160. // Compute value
  45161. var repeatCount = (ratio / range) >> 0;
  45162. var currentFrame = returnValue ? from + ratio % range : to;
  45163. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  45164. // Set value
  45165. this.setValue(currentValue);
  45166. // Check events
  45167. var events = this._animation.getEvents();
  45168. for (var index = 0; index < events.length; index++) {
  45169. // Make sure current frame has passed event frame and that event frame is within the current range
  45170. // Also, handle both forward and reverse animations
  45171. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  45172. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  45173. var event = events[index];
  45174. if (!event.isDone) {
  45175. // If event should be done only once, remove it.
  45176. if (event.onlyOnce) {
  45177. events.splice(index, 1);
  45178. index--;
  45179. }
  45180. event.isDone = true;
  45181. event.action();
  45182. } // Don't do anything if the event has already be done.
  45183. }
  45184. else if (events[index].isDone && !events[index].onlyOnce) {
  45185. // reset event, the animation is looping
  45186. events[index].isDone = false;
  45187. }
  45188. }
  45189. if (!returnValue) {
  45190. this._stopped = true;
  45191. }
  45192. return returnValue;
  45193. };
  45194. return RuntimeAnimation;
  45195. }());
  45196. BABYLON.RuntimeAnimation = RuntimeAnimation;
  45197. })(BABYLON || (BABYLON = {}));
  45198. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  45199. var BABYLON;
  45200. (function (BABYLON) {
  45201. var Animatable = /** @class */ (function () {
  45202. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  45203. if (fromFrame === void 0) { fromFrame = 0; }
  45204. if (toFrame === void 0) { toFrame = 100; }
  45205. if (loopAnimation === void 0) { loopAnimation = false; }
  45206. if (speedRatio === void 0) { speedRatio = 1.0; }
  45207. this.target = target;
  45208. this.fromFrame = fromFrame;
  45209. this.toFrame = toFrame;
  45210. this.loopAnimation = loopAnimation;
  45211. this.onAnimationEnd = onAnimationEnd;
  45212. this._localDelayOffset = null;
  45213. this._pausedDelay = null;
  45214. this._runtimeAnimations = new Array();
  45215. this._paused = false;
  45216. this._speedRatio = 1;
  45217. this.animationStarted = false;
  45218. if (animations) {
  45219. this.appendAnimations(target, animations);
  45220. }
  45221. this._speedRatio = speedRatio;
  45222. this._scene = scene;
  45223. scene._activeAnimatables.push(this);
  45224. }
  45225. Object.defineProperty(Animatable.prototype, "speedRatio", {
  45226. get: function () {
  45227. return this._speedRatio;
  45228. },
  45229. set: function (value) {
  45230. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  45231. var animation = this._runtimeAnimations[index];
  45232. animation._prepareForSpeedRatioChange(value);
  45233. }
  45234. this._speedRatio = value;
  45235. },
  45236. enumerable: true,
  45237. configurable: true
  45238. });
  45239. // Methods
  45240. Animatable.prototype.getAnimations = function () {
  45241. return this._runtimeAnimations;
  45242. };
  45243. Animatable.prototype.appendAnimations = function (target, animations) {
  45244. for (var index = 0; index < animations.length; index++) {
  45245. var animation = animations[index];
  45246. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  45247. }
  45248. };
  45249. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45250. var runtimeAnimations = this._runtimeAnimations;
  45251. for (var index = 0; index < runtimeAnimations.length; index++) {
  45252. if (runtimeAnimations[index].animation.targetProperty === property) {
  45253. return runtimeAnimations[index].animation;
  45254. }
  45255. }
  45256. return null;
  45257. };
  45258. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45259. var runtimeAnimations = this._runtimeAnimations;
  45260. for (var index = 0; index < runtimeAnimations.length; index++) {
  45261. if (runtimeAnimations[index].animation.targetProperty === property) {
  45262. return runtimeAnimations[index];
  45263. }
  45264. }
  45265. return null;
  45266. };
  45267. Animatable.prototype.reset = function () {
  45268. var runtimeAnimations = this._runtimeAnimations;
  45269. for (var index = 0; index < runtimeAnimations.length; index++) {
  45270. runtimeAnimations[index].reset();
  45271. }
  45272. // Reset to original value
  45273. for (index = 0; index < runtimeAnimations.length; index++) {
  45274. var animation = runtimeAnimations[index];
  45275. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45276. }
  45277. this._localDelayOffset = null;
  45278. this._pausedDelay = null;
  45279. };
  45280. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45281. var runtimeAnimations = this._runtimeAnimations;
  45282. for (var index = 0; index < runtimeAnimations.length; index++) {
  45283. runtimeAnimations[index].animation.enableBlending = true;
  45284. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45285. }
  45286. };
  45287. Animatable.prototype.disableBlending = function () {
  45288. var runtimeAnimations = this._runtimeAnimations;
  45289. for (var index = 0; index < runtimeAnimations.length; index++) {
  45290. runtimeAnimations[index].animation.enableBlending = false;
  45291. }
  45292. };
  45293. Animatable.prototype.goToFrame = function (frame) {
  45294. var runtimeAnimations = this._runtimeAnimations;
  45295. if (runtimeAnimations[0]) {
  45296. var fps = runtimeAnimations[0].animation.framePerSecond;
  45297. var currentFrame = runtimeAnimations[0].currentFrame;
  45298. var adjustTime = frame - currentFrame;
  45299. var delay = adjustTime * 1000 / fps;
  45300. if (this._localDelayOffset === null) {
  45301. this._localDelayOffset = 0;
  45302. }
  45303. this._localDelayOffset -= delay;
  45304. }
  45305. for (var index = 0; index < runtimeAnimations.length; index++) {
  45306. runtimeAnimations[index].goToFrame(frame);
  45307. }
  45308. };
  45309. Animatable.prototype.pause = function () {
  45310. if (this._paused) {
  45311. return;
  45312. }
  45313. this._paused = true;
  45314. };
  45315. Animatable.prototype.restart = function () {
  45316. this._paused = false;
  45317. };
  45318. Animatable.prototype.stop = function (animationName) {
  45319. if (animationName) {
  45320. var idx = this._scene._activeAnimatables.indexOf(this);
  45321. if (idx > -1) {
  45322. var runtimeAnimations = this._runtimeAnimations;
  45323. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45324. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45325. continue;
  45326. }
  45327. runtimeAnimations[index].dispose();
  45328. runtimeAnimations.splice(index, 1);
  45329. }
  45330. if (runtimeAnimations.length == 0) {
  45331. this._scene._activeAnimatables.splice(idx, 1);
  45332. if (this.onAnimationEnd) {
  45333. this.onAnimationEnd();
  45334. }
  45335. }
  45336. }
  45337. }
  45338. else {
  45339. var index = this._scene._activeAnimatables.indexOf(this);
  45340. if (index > -1) {
  45341. this._scene._activeAnimatables.splice(index, 1);
  45342. var runtimeAnimations = this._runtimeAnimations;
  45343. for (var index = 0; index < runtimeAnimations.length; index++) {
  45344. runtimeAnimations[index].dispose();
  45345. }
  45346. if (this.onAnimationEnd) {
  45347. this.onAnimationEnd();
  45348. }
  45349. }
  45350. }
  45351. };
  45352. Animatable.prototype._animate = function (delay) {
  45353. if (this._paused) {
  45354. this.animationStarted = false;
  45355. if (this._pausedDelay === null) {
  45356. this._pausedDelay = delay;
  45357. }
  45358. return true;
  45359. }
  45360. if (this._localDelayOffset === null) {
  45361. this._localDelayOffset = delay;
  45362. this._pausedDelay = null;
  45363. }
  45364. else if (this._pausedDelay !== null) {
  45365. this._localDelayOffset += delay - this._pausedDelay;
  45366. this._pausedDelay = null;
  45367. }
  45368. // Animating
  45369. var running = false;
  45370. var runtimeAnimations = this._runtimeAnimations;
  45371. var index;
  45372. for (index = 0; index < runtimeAnimations.length; index++) {
  45373. var animation = runtimeAnimations[index];
  45374. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45375. running = running || isRunning;
  45376. }
  45377. this.animationStarted = running;
  45378. if (!running) {
  45379. // Remove from active animatables
  45380. index = this._scene._activeAnimatables.indexOf(this);
  45381. this._scene._activeAnimatables.splice(index, 1);
  45382. // Dispose all runtime animations
  45383. for (index = 0; index < runtimeAnimations.length; index++) {
  45384. runtimeAnimations[index].dispose();
  45385. }
  45386. }
  45387. if (!running && this.onAnimationEnd) {
  45388. this.onAnimationEnd();
  45389. this.onAnimationEnd = null;
  45390. }
  45391. return running;
  45392. };
  45393. return Animatable;
  45394. }());
  45395. BABYLON.Animatable = Animatable;
  45396. })(BABYLON || (BABYLON = {}));
  45397. //# sourceMappingURL=babylon.animatable.js.map
  45398. var BABYLON;
  45399. (function (BABYLON) {
  45400. var EasingFunction = /** @class */ (function () {
  45401. function EasingFunction() {
  45402. // Properties
  45403. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45404. }
  45405. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45406. get: function () {
  45407. return EasingFunction._EASINGMODE_EASEIN;
  45408. },
  45409. enumerable: true,
  45410. configurable: true
  45411. });
  45412. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45413. get: function () {
  45414. return EasingFunction._EASINGMODE_EASEOUT;
  45415. },
  45416. enumerable: true,
  45417. configurable: true
  45418. });
  45419. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45420. get: function () {
  45421. return EasingFunction._EASINGMODE_EASEINOUT;
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45427. var n = Math.min(Math.max(easingMode, 0), 2);
  45428. this._easingMode = n;
  45429. };
  45430. EasingFunction.prototype.getEasingMode = function () {
  45431. return this._easingMode;
  45432. };
  45433. EasingFunction.prototype.easeInCore = function (gradient) {
  45434. throw new Error('You must implement this method');
  45435. };
  45436. EasingFunction.prototype.ease = function (gradient) {
  45437. switch (this._easingMode) {
  45438. case EasingFunction.EASINGMODE_EASEIN:
  45439. return this.easeInCore(gradient);
  45440. case EasingFunction.EASINGMODE_EASEOUT:
  45441. return (1 - this.easeInCore(1 - gradient));
  45442. }
  45443. if (gradient >= 0.5) {
  45444. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45445. }
  45446. return (this.easeInCore(gradient * 2) * 0.5);
  45447. };
  45448. //Statics
  45449. EasingFunction._EASINGMODE_EASEIN = 0;
  45450. EasingFunction._EASINGMODE_EASEOUT = 1;
  45451. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45452. return EasingFunction;
  45453. }());
  45454. BABYLON.EasingFunction = EasingFunction;
  45455. var CircleEase = /** @class */ (function (_super) {
  45456. __extends(CircleEase, _super);
  45457. function CircleEase() {
  45458. return _super !== null && _super.apply(this, arguments) || this;
  45459. }
  45460. CircleEase.prototype.easeInCore = function (gradient) {
  45461. gradient = Math.max(0, Math.min(1, gradient));
  45462. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45463. };
  45464. return CircleEase;
  45465. }(EasingFunction));
  45466. BABYLON.CircleEase = CircleEase;
  45467. var BackEase = /** @class */ (function (_super) {
  45468. __extends(BackEase, _super);
  45469. function BackEase(amplitude) {
  45470. if (amplitude === void 0) { amplitude = 1; }
  45471. var _this = _super.call(this) || this;
  45472. _this.amplitude = amplitude;
  45473. return _this;
  45474. }
  45475. BackEase.prototype.easeInCore = function (gradient) {
  45476. var num = Math.max(0, this.amplitude);
  45477. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45478. };
  45479. return BackEase;
  45480. }(EasingFunction));
  45481. BABYLON.BackEase = BackEase;
  45482. var BounceEase = /** @class */ (function (_super) {
  45483. __extends(BounceEase, _super);
  45484. function BounceEase(bounces, bounciness) {
  45485. if (bounces === void 0) { bounces = 3; }
  45486. if (bounciness === void 0) { bounciness = 2; }
  45487. var _this = _super.call(this) || this;
  45488. _this.bounces = bounces;
  45489. _this.bounciness = bounciness;
  45490. return _this;
  45491. }
  45492. BounceEase.prototype.easeInCore = function (gradient) {
  45493. var y = Math.max(0.0, this.bounces);
  45494. var bounciness = this.bounciness;
  45495. if (bounciness <= 1.0) {
  45496. bounciness = 1.001;
  45497. }
  45498. var num9 = Math.pow(bounciness, y);
  45499. var num5 = 1.0 - bounciness;
  45500. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45501. var num15 = gradient * num4;
  45502. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45503. var num3 = Math.floor(num65);
  45504. var num13 = num3 + 1.0;
  45505. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45506. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45507. var num7 = (num8 + num12) * 0.5;
  45508. var num6 = gradient - num7;
  45509. var num2 = num7 - num8;
  45510. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45511. };
  45512. return BounceEase;
  45513. }(EasingFunction));
  45514. BABYLON.BounceEase = BounceEase;
  45515. var CubicEase = /** @class */ (function (_super) {
  45516. __extends(CubicEase, _super);
  45517. function CubicEase() {
  45518. return _super !== null && _super.apply(this, arguments) || this;
  45519. }
  45520. CubicEase.prototype.easeInCore = function (gradient) {
  45521. return (gradient * gradient * gradient);
  45522. };
  45523. return CubicEase;
  45524. }(EasingFunction));
  45525. BABYLON.CubicEase = CubicEase;
  45526. var ElasticEase = /** @class */ (function (_super) {
  45527. __extends(ElasticEase, _super);
  45528. function ElasticEase(oscillations, springiness) {
  45529. if (oscillations === void 0) { oscillations = 3; }
  45530. if (springiness === void 0) { springiness = 3; }
  45531. var _this = _super.call(this) || this;
  45532. _this.oscillations = oscillations;
  45533. _this.springiness = springiness;
  45534. return _this;
  45535. }
  45536. ElasticEase.prototype.easeInCore = function (gradient) {
  45537. var num2;
  45538. var num3 = Math.max(0.0, this.oscillations);
  45539. var num = Math.max(0.0, this.springiness);
  45540. if (num == 0) {
  45541. num2 = gradient;
  45542. }
  45543. else {
  45544. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45545. }
  45546. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45547. };
  45548. return ElasticEase;
  45549. }(EasingFunction));
  45550. BABYLON.ElasticEase = ElasticEase;
  45551. var ExponentialEase = /** @class */ (function (_super) {
  45552. __extends(ExponentialEase, _super);
  45553. function ExponentialEase(exponent) {
  45554. if (exponent === void 0) { exponent = 2; }
  45555. var _this = _super.call(this) || this;
  45556. _this.exponent = exponent;
  45557. return _this;
  45558. }
  45559. ExponentialEase.prototype.easeInCore = function (gradient) {
  45560. if (this.exponent <= 0) {
  45561. return gradient;
  45562. }
  45563. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45564. };
  45565. return ExponentialEase;
  45566. }(EasingFunction));
  45567. BABYLON.ExponentialEase = ExponentialEase;
  45568. var PowerEase = /** @class */ (function (_super) {
  45569. __extends(PowerEase, _super);
  45570. function PowerEase(power) {
  45571. if (power === void 0) { power = 2; }
  45572. var _this = _super.call(this) || this;
  45573. _this.power = power;
  45574. return _this;
  45575. }
  45576. PowerEase.prototype.easeInCore = function (gradient) {
  45577. var y = Math.max(0.0, this.power);
  45578. return Math.pow(gradient, y);
  45579. };
  45580. return PowerEase;
  45581. }(EasingFunction));
  45582. BABYLON.PowerEase = PowerEase;
  45583. var QuadraticEase = /** @class */ (function (_super) {
  45584. __extends(QuadraticEase, _super);
  45585. function QuadraticEase() {
  45586. return _super !== null && _super.apply(this, arguments) || this;
  45587. }
  45588. QuadraticEase.prototype.easeInCore = function (gradient) {
  45589. return (gradient * gradient);
  45590. };
  45591. return QuadraticEase;
  45592. }(EasingFunction));
  45593. BABYLON.QuadraticEase = QuadraticEase;
  45594. var QuarticEase = /** @class */ (function (_super) {
  45595. __extends(QuarticEase, _super);
  45596. function QuarticEase() {
  45597. return _super !== null && _super.apply(this, arguments) || this;
  45598. }
  45599. QuarticEase.prototype.easeInCore = function (gradient) {
  45600. return (gradient * gradient * gradient * gradient);
  45601. };
  45602. return QuarticEase;
  45603. }(EasingFunction));
  45604. BABYLON.QuarticEase = QuarticEase;
  45605. var QuinticEase = /** @class */ (function (_super) {
  45606. __extends(QuinticEase, _super);
  45607. function QuinticEase() {
  45608. return _super !== null && _super.apply(this, arguments) || this;
  45609. }
  45610. QuinticEase.prototype.easeInCore = function (gradient) {
  45611. return (gradient * gradient * gradient * gradient * gradient);
  45612. };
  45613. return QuinticEase;
  45614. }(EasingFunction));
  45615. BABYLON.QuinticEase = QuinticEase;
  45616. var SineEase = /** @class */ (function (_super) {
  45617. __extends(SineEase, _super);
  45618. function SineEase() {
  45619. return _super !== null && _super.apply(this, arguments) || this;
  45620. }
  45621. SineEase.prototype.easeInCore = function (gradient) {
  45622. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45623. };
  45624. return SineEase;
  45625. }(EasingFunction));
  45626. BABYLON.SineEase = SineEase;
  45627. var BezierCurveEase = /** @class */ (function (_super) {
  45628. __extends(BezierCurveEase, _super);
  45629. function BezierCurveEase(x1, y1, x2, y2) {
  45630. if (x1 === void 0) { x1 = 0; }
  45631. if (y1 === void 0) { y1 = 0; }
  45632. if (x2 === void 0) { x2 = 1; }
  45633. if (y2 === void 0) { y2 = 1; }
  45634. var _this = _super.call(this) || this;
  45635. _this.x1 = x1;
  45636. _this.y1 = y1;
  45637. _this.x2 = x2;
  45638. _this.y2 = y2;
  45639. return _this;
  45640. }
  45641. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45642. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45643. };
  45644. return BezierCurveEase;
  45645. }(EasingFunction));
  45646. BABYLON.BezierCurveEase = BezierCurveEase;
  45647. })(BABYLON || (BABYLON = {}));
  45648. //# sourceMappingURL=babylon.easing.js.map
  45649. var BABYLON;
  45650. (function (BABYLON) {
  45651. var Condition = /** @class */ (function () {
  45652. function Condition(actionManager) {
  45653. this._actionManager = actionManager;
  45654. }
  45655. Condition.prototype.isValid = function () {
  45656. return true;
  45657. };
  45658. Condition.prototype._getProperty = function (propertyPath) {
  45659. return this._actionManager._getProperty(propertyPath);
  45660. };
  45661. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45662. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45663. };
  45664. Condition.prototype.serialize = function () {
  45665. };
  45666. Condition.prototype._serialize = function (serializedCondition) {
  45667. return {
  45668. type: 2,
  45669. children: [],
  45670. name: serializedCondition.name,
  45671. properties: serializedCondition.properties
  45672. };
  45673. };
  45674. return Condition;
  45675. }());
  45676. BABYLON.Condition = Condition;
  45677. var ValueCondition = /** @class */ (function (_super) {
  45678. __extends(ValueCondition, _super);
  45679. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45680. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45681. var _this = _super.call(this, actionManager) || this;
  45682. _this.propertyPath = propertyPath;
  45683. _this.value = value;
  45684. _this.operator = operator;
  45685. _this._target = target;
  45686. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45687. _this._property = _this._getProperty(_this.propertyPath);
  45688. return _this;
  45689. }
  45690. Object.defineProperty(ValueCondition, "IsEqual", {
  45691. get: function () {
  45692. return ValueCondition._IsEqual;
  45693. },
  45694. enumerable: true,
  45695. configurable: true
  45696. });
  45697. Object.defineProperty(ValueCondition, "IsDifferent", {
  45698. get: function () {
  45699. return ValueCondition._IsDifferent;
  45700. },
  45701. enumerable: true,
  45702. configurable: true
  45703. });
  45704. Object.defineProperty(ValueCondition, "IsGreater", {
  45705. get: function () {
  45706. return ValueCondition._IsGreater;
  45707. },
  45708. enumerable: true,
  45709. configurable: true
  45710. });
  45711. Object.defineProperty(ValueCondition, "IsLesser", {
  45712. get: function () {
  45713. return ValueCondition._IsLesser;
  45714. },
  45715. enumerable: true,
  45716. configurable: true
  45717. });
  45718. // Methods
  45719. ValueCondition.prototype.isValid = function () {
  45720. switch (this.operator) {
  45721. case ValueCondition.IsGreater:
  45722. return this._effectiveTarget[this._property] > this.value;
  45723. case ValueCondition.IsLesser:
  45724. return this._effectiveTarget[this._property] < this.value;
  45725. case ValueCondition.IsEqual:
  45726. case ValueCondition.IsDifferent:
  45727. var check;
  45728. if (this.value.equals) {
  45729. check = this.value.equals(this._effectiveTarget[this._property]);
  45730. }
  45731. else {
  45732. check = this.value === this._effectiveTarget[this._property];
  45733. }
  45734. return this.operator === ValueCondition.IsEqual ? check : !check;
  45735. }
  45736. return false;
  45737. };
  45738. ValueCondition.prototype.serialize = function () {
  45739. return this._serialize({
  45740. name: "ValueCondition",
  45741. properties: [
  45742. BABYLON.Action._GetTargetProperty(this._target),
  45743. { name: "propertyPath", value: this.propertyPath },
  45744. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45745. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45746. ]
  45747. });
  45748. };
  45749. ValueCondition.GetOperatorName = function (operator) {
  45750. switch (operator) {
  45751. case ValueCondition._IsEqual: return "IsEqual";
  45752. case ValueCondition._IsDifferent: return "IsDifferent";
  45753. case ValueCondition._IsGreater: return "IsGreater";
  45754. case ValueCondition._IsLesser: return "IsLesser";
  45755. default: return "";
  45756. }
  45757. };
  45758. // Statics
  45759. ValueCondition._IsEqual = 0;
  45760. ValueCondition._IsDifferent = 1;
  45761. ValueCondition._IsGreater = 2;
  45762. ValueCondition._IsLesser = 3;
  45763. return ValueCondition;
  45764. }(Condition));
  45765. BABYLON.ValueCondition = ValueCondition;
  45766. var PredicateCondition = /** @class */ (function (_super) {
  45767. __extends(PredicateCondition, _super);
  45768. function PredicateCondition(actionManager, predicate) {
  45769. var _this = _super.call(this, actionManager) || this;
  45770. _this.predicate = predicate;
  45771. return _this;
  45772. }
  45773. PredicateCondition.prototype.isValid = function () {
  45774. return this.predicate();
  45775. };
  45776. return PredicateCondition;
  45777. }(Condition));
  45778. BABYLON.PredicateCondition = PredicateCondition;
  45779. var StateCondition = /** @class */ (function (_super) {
  45780. __extends(StateCondition, _super);
  45781. function StateCondition(actionManager, target, value) {
  45782. var _this = _super.call(this, actionManager) || this;
  45783. _this.value = value;
  45784. _this._target = target;
  45785. return _this;
  45786. }
  45787. // Methods
  45788. StateCondition.prototype.isValid = function () {
  45789. return this._target.state === this.value;
  45790. };
  45791. StateCondition.prototype.serialize = function () {
  45792. return this._serialize({
  45793. name: "StateCondition",
  45794. properties: [
  45795. BABYLON.Action._GetTargetProperty(this._target),
  45796. { name: "value", value: this.value }
  45797. ]
  45798. });
  45799. };
  45800. return StateCondition;
  45801. }(Condition));
  45802. BABYLON.StateCondition = StateCondition;
  45803. })(BABYLON || (BABYLON = {}));
  45804. //# sourceMappingURL=babylon.condition.js.map
  45805. var BABYLON;
  45806. (function (BABYLON) {
  45807. var Action = /** @class */ (function () {
  45808. function Action(triggerOptions, condition) {
  45809. this.triggerOptions = triggerOptions;
  45810. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45811. if (triggerOptions.parameter) {
  45812. this.trigger = triggerOptions.trigger;
  45813. this._triggerParameter = triggerOptions.parameter;
  45814. }
  45815. else {
  45816. this.trigger = triggerOptions;
  45817. }
  45818. this._nextActiveAction = this;
  45819. this._condition = condition;
  45820. }
  45821. // Methods
  45822. Action.prototype._prepare = function () {
  45823. };
  45824. Action.prototype.getTriggerParameter = function () {
  45825. return this._triggerParameter;
  45826. };
  45827. Action.prototype._executeCurrent = function (evt) {
  45828. if (this._nextActiveAction._condition) {
  45829. var condition = this._nextActiveAction._condition;
  45830. var currentRenderId = this._actionManager.getScene().getRenderId();
  45831. // We cache the current evaluation for the current frame
  45832. if (condition._evaluationId === currentRenderId) {
  45833. if (!condition._currentResult) {
  45834. return;
  45835. }
  45836. }
  45837. else {
  45838. condition._evaluationId = currentRenderId;
  45839. if (!condition.isValid()) {
  45840. condition._currentResult = false;
  45841. return;
  45842. }
  45843. condition._currentResult = true;
  45844. }
  45845. }
  45846. this.onBeforeExecuteObservable.notifyObservers(this);
  45847. this._nextActiveAction.execute(evt);
  45848. this.skipToNextActiveAction();
  45849. };
  45850. Action.prototype.execute = function (evt) {
  45851. };
  45852. Action.prototype.skipToNextActiveAction = function () {
  45853. if (this._nextActiveAction._child) {
  45854. if (!this._nextActiveAction._child._actionManager) {
  45855. this._nextActiveAction._child._actionManager = this._actionManager;
  45856. }
  45857. this._nextActiveAction = this._nextActiveAction._child;
  45858. }
  45859. else {
  45860. this._nextActiveAction = this;
  45861. }
  45862. };
  45863. Action.prototype.then = function (action) {
  45864. this._child = action;
  45865. action._actionManager = this._actionManager;
  45866. action._prepare();
  45867. return action;
  45868. };
  45869. Action.prototype._getProperty = function (propertyPath) {
  45870. return this._actionManager._getProperty(propertyPath);
  45871. };
  45872. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45873. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45874. };
  45875. Action.prototype.serialize = function (parent) {
  45876. };
  45877. // Called by BABYLON.Action objects in serialize(...). Internal use
  45878. Action.prototype._serialize = function (serializedAction, parent) {
  45879. var serializationObject = {
  45880. type: 1,
  45881. children: [],
  45882. name: serializedAction.name,
  45883. properties: serializedAction.properties || []
  45884. };
  45885. // Serialize child
  45886. if (this._child) {
  45887. this._child.serialize(serializationObject);
  45888. }
  45889. // Check if "this" has a condition
  45890. if (this._condition) {
  45891. var serializedCondition = this._condition.serialize();
  45892. serializedCondition.children.push(serializationObject);
  45893. if (parent) {
  45894. parent.children.push(serializedCondition);
  45895. }
  45896. return serializedCondition;
  45897. }
  45898. if (parent) {
  45899. parent.children.push(serializationObject);
  45900. }
  45901. return serializationObject;
  45902. };
  45903. Action._SerializeValueAsString = function (value) {
  45904. if (typeof value === "number") {
  45905. return value.toString();
  45906. }
  45907. if (typeof value === "boolean") {
  45908. return value ? "true" : "false";
  45909. }
  45910. if (value instanceof BABYLON.Vector2) {
  45911. return value.x + ", " + value.y;
  45912. }
  45913. if (value instanceof BABYLON.Vector3) {
  45914. return value.x + ", " + value.y + ", " + value.z;
  45915. }
  45916. if (value instanceof BABYLON.Color3) {
  45917. return value.r + ", " + value.g + ", " + value.b;
  45918. }
  45919. if (value instanceof BABYLON.Color4) {
  45920. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45921. }
  45922. return value; // string
  45923. };
  45924. Action._GetTargetProperty = function (target) {
  45925. return {
  45926. name: "target",
  45927. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45928. : target instanceof BABYLON.Light ? "LightProperties"
  45929. : target instanceof BABYLON.Camera ? "CameraProperties"
  45930. : "SceneProperties",
  45931. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45932. };
  45933. };
  45934. return Action;
  45935. }());
  45936. BABYLON.Action = Action;
  45937. })(BABYLON || (BABYLON = {}));
  45938. //# sourceMappingURL=babylon.action.js.map
  45939. var BABYLON;
  45940. (function (BABYLON) {
  45941. /**
  45942. * ActionEvent is the event beint sent when an action is triggered.
  45943. */
  45944. var ActionEvent = /** @class */ (function () {
  45945. /**
  45946. * @param source The mesh or sprite that triggered the action.
  45947. * @param pointerX The X mouse cursor position at the time of the event
  45948. * @param pointerY The Y mouse cursor position at the time of the event
  45949. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45950. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45951. */
  45952. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45953. this.source = source;
  45954. this.pointerX = pointerX;
  45955. this.pointerY = pointerY;
  45956. this.meshUnderPointer = meshUnderPointer;
  45957. this.sourceEvent = sourceEvent;
  45958. this.additionalData = additionalData;
  45959. }
  45960. /**
  45961. * Helper function to auto-create an ActionEvent from a source mesh.
  45962. * @param source The source mesh that triggered the event
  45963. * @param evt {Event} The original (browser) event
  45964. */
  45965. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45966. var scene = source.getScene();
  45967. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45968. };
  45969. /**
  45970. * Helper function to auto-create an ActionEvent from a source mesh.
  45971. * @param source The source sprite that triggered the event
  45972. * @param scene Scene associated with the sprite
  45973. * @param evt {Event} The original (browser) event
  45974. */
  45975. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45976. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45977. };
  45978. /**
  45979. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45980. * @param scene the scene where the event occurred
  45981. * @param evt {Event} The original (browser) event
  45982. */
  45983. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45984. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45985. };
  45986. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45987. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45988. };
  45989. return ActionEvent;
  45990. }());
  45991. BABYLON.ActionEvent = ActionEvent;
  45992. /**
  45993. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45994. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45995. */
  45996. var ActionManager = /** @class */ (function () {
  45997. function ActionManager(scene) {
  45998. // Members
  45999. this.actions = new Array();
  46000. this.hoverCursor = '';
  46001. this._scene = scene;
  46002. scene._actionManagers.push(this);
  46003. }
  46004. Object.defineProperty(ActionManager, "NothingTrigger", {
  46005. get: function () {
  46006. return ActionManager._NothingTrigger;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46012. get: function () {
  46013. return ActionManager._OnPickTrigger;
  46014. },
  46015. enumerable: true,
  46016. configurable: true
  46017. });
  46018. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46019. get: function () {
  46020. return ActionManager._OnLeftPickTrigger;
  46021. },
  46022. enumerable: true,
  46023. configurable: true
  46024. });
  46025. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46026. get: function () {
  46027. return ActionManager._OnRightPickTrigger;
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46033. get: function () {
  46034. return ActionManager._OnCenterPickTrigger;
  46035. },
  46036. enumerable: true,
  46037. configurable: true
  46038. });
  46039. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46040. get: function () {
  46041. return ActionManager._OnPickDownTrigger;
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46047. get: function () {
  46048. return ActionManager._OnDoublePickTrigger;
  46049. },
  46050. enumerable: true,
  46051. configurable: true
  46052. });
  46053. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46054. get: function () {
  46055. return ActionManager._OnPickUpTrigger;
  46056. },
  46057. enumerable: true,
  46058. configurable: true
  46059. });
  46060. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46061. /// This trigger will only be raised if you also declared a OnPickDown
  46062. get: function () {
  46063. return ActionManager._OnPickOutTrigger;
  46064. },
  46065. enumerable: true,
  46066. configurable: true
  46067. });
  46068. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46069. get: function () {
  46070. return ActionManager._OnLongPressTrigger;
  46071. },
  46072. enumerable: true,
  46073. configurable: true
  46074. });
  46075. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46076. get: function () {
  46077. return ActionManager._OnPointerOverTrigger;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46083. get: function () {
  46084. return ActionManager._OnPointerOutTrigger;
  46085. },
  46086. enumerable: true,
  46087. configurable: true
  46088. });
  46089. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46090. get: function () {
  46091. return ActionManager._OnEveryFrameTrigger;
  46092. },
  46093. enumerable: true,
  46094. configurable: true
  46095. });
  46096. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46097. get: function () {
  46098. return ActionManager._OnIntersectionEnterTrigger;
  46099. },
  46100. enumerable: true,
  46101. configurable: true
  46102. });
  46103. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46104. get: function () {
  46105. return ActionManager._OnIntersectionExitTrigger;
  46106. },
  46107. enumerable: true,
  46108. configurable: true
  46109. });
  46110. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46111. get: function () {
  46112. return ActionManager._OnKeyDownTrigger;
  46113. },
  46114. enumerable: true,
  46115. configurable: true
  46116. });
  46117. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46118. get: function () {
  46119. return ActionManager._OnKeyUpTrigger;
  46120. },
  46121. enumerable: true,
  46122. configurable: true
  46123. });
  46124. // Methods
  46125. ActionManager.prototype.dispose = function () {
  46126. var index = this._scene._actionManagers.indexOf(this);
  46127. for (var i = 0; i < this.actions.length; i++) {
  46128. var action = this.actions[i];
  46129. ActionManager.Triggers[action.trigger]--;
  46130. if (ActionManager.Triggers[action.trigger] === 0) {
  46131. delete ActionManager.Triggers[action.trigger];
  46132. }
  46133. }
  46134. if (index > -1) {
  46135. this._scene._actionManagers.splice(index, 1);
  46136. }
  46137. };
  46138. ActionManager.prototype.getScene = function () {
  46139. return this._scene;
  46140. };
  46141. /**
  46142. * Does this action manager handles actions of any of the given triggers
  46143. * @param {number[]} triggers - the triggers to be tested
  46144. * @return {boolean} whether one (or more) of the triggers is handeled
  46145. */
  46146. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46147. for (var index = 0; index < this.actions.length; index++) {
  46148. var action = this.actions[index];
  46149. if (triggers.indexOf(action.trigger) > -1) {
  46150. return true;
  46151. }
  46152. }
  46153. return false;
  46154. };
  46155. /**
  46156. * Does this action manager handles actions of a given trigger
  46157. * @param {number} trigger - the trigger to be tested
  46158. * @return {boolean} whether the trigger is handeled
  46159. */
  46160. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46161. for (var index = 0; index < this.actions.length; index++) {
  46162. var action = this.actions[index];
  46163. if (action.trigger === trigger) {
  46164. return true;
  46165. }
  46166. }
  46167. return false;
  46168. };
  46169. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46170. /**
  46171. * Does this action manager has pointer triggers
  46172. * @return {boolean} whether or not it has pointer triggers
  46173. */
  46174. get: function () {
  46175. for (var index = 0; index < this.actions.length; index++) {
  46176. var action = this.actions[index];
  46177. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46178. return true;
  46179. }
  46180. }
  46181. return false;
  46182. },
  46183. enumerable: true,
  46184. configurable: true
  46185. });
  46186. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46187. /**
  46188. * Does this action manager has pick triggers
  46189. * @return {boolean} whether or not it has pick triggers
  46190. */
  46191. get: function () {
  46192. for (var index = 0; index < this.actions.length; index++) {
  46193. var action = this.actions[index];
  46194. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46195. return true;
  46196. }
  46197. }
  46198. return false;
  46199. },
  46200. enumerable: true,
  46201. configurable: true
  46202. });
  46203. Object.defineProperty(ActionManager, "HasTriggers", {
  46204. /**
  46205. * Does exist one action manager with at least one trigger
  46206. * @return {boolean} whether or not it exists one action manager with one trigger
  46207. **/
  46208. get: function () {
  46209. for (var t in ActionManager.Triggers) {
  46210. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46211. return true;
  46212. }
  46213. }
  46214. return false;
  46215. },
  46216. enumerable: true,
  46217. configurable: true
  46218. });
  46219. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46220. /**
  46221. * Does exist one action manager with at least one pick trigger
  46222. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46223. **/
  46224. get: function () {
  46225. for (var t in ActionManager.Triggers) {
  46226. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46227. var t_int = parseInt(t);
  46228. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46229. return true;
  46230. }
  46231. }
  46232. }
  46233. return false;
  46234. },
  46235. enumerable: true,
  46236. configurable: true
  46237. });
  46238. /**
  46239. * Does exist one action manager that handles actions of a given trigger
  46240. * @param {number} trigger - the trigger to be tested
  46241. * @return {boolean} whether the trigger is handeled by at least one action manager
  46242. **/
  46243. ActionManager.HasSpecificTrigger = function (trigger) {
  46244. for (var t in ActionManager.Triggers) {
  46245. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46246. var t_int = parseInt(t);
  46247. if (t_int === trigger) {
  46248. return true;
  46249. }
  46250. }
  46251. }
  46252. return false;
  46253. };
  46254. /**
  46255. * Registers an action to this action manager
  46256. * @param {BABYLON.Action} action - the action to be registered
  46257. * @return {BABYLON.Action} the action amended (prepared) after registration
  46258. */
  46259. ActionManager.prototype.registerAction = function (action) {
  46260. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46261. if (this.getScene().actionManager !== this) {
  46262. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46263. return null;
  46264. }
  46265. }
  46266. this.actions.push(action);
  46267. if (ActionManager.Triggers[action.trigger]) {
  46268. ActionManager.Triggers[action.trigger]++;
  46269. }
  46270. else {
  46271. ActionManager.Triggers[action.trigger] = 1;
  46272. }
  46273. action._actionManager = this;
  46274. action._prepare();
  46275. return action;
  46276. };
  46277. /**
  46278. * Unregisters an action to this action manager
  46279. * @param action The action to be unregistered
  46280. * @return whether the action has been unregistered
  46281. */
  46282. ActionManager.prototype.unregisterAction = function (action) {
  46283. var index = this.actions.indexOf(action);
  46284. if (index !== -1) {
  46285. this.actions.splice(index, 1);
  46286. ActionManager.Triggers[action.trigger] -= 1;
  46287. if (ActionManager.Triggers[action.trigger] === 0) {
  46288. delete ActionManager.Triggers[action.trigger];
  46289. }
  46290. delete action._actionManager;
  46291. return true;
  46292. }
  46293. return false;
  46294. };
  46295. /**
  46296. * Process a specific trigger
  46297. * @param {number} trigger - the trigger to process
  46298. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46299. */
  46300. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46301. for (var index = 0; index < this.actions.length; index++) {
  46302. var action = this.actions[index];
  46303. if (action.trigger === trigger) {
  46304. if (evt) {
  46305. if (trigger === ActionManager.OnKeyUpTrigger
  46306. || trigger === ActionManager.OnKeyDownTrigger) {
  46307. var parameter = action.getTriggerParameter();
  46308. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46309. if (!parameter.toLowerCase) {
  46310. continue;
  46311. }
  46312. var lowerCase = parameter.toLowerCase();
  46313. if (lowerCase !== evt.sourceEvent.key) {
  46314. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46315. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46316. if (actualkey !== lowerCase) {
  46317. continue;
  46318. }
  46319. }
  46320. }
  46321. }
  46322. }
  46323. action._executeCurrent(evt);
  46324. }
  46325. }
  46326. };
  46327. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46328. var properties = propertyPath.split(".");
  46329. for (var index = 0; index < properties.length - 1; index++) {
  46330. target = target[properties[index]];
  46331. }
  46332. return target;
  46333. };
  46334. ActionManager.prototype._getProperty = function (propertyPath) {
  46335. var properties = propertyPath.split(".");
  46336. return properties[properties.length - 1];
  46337. };
  46338. ActionManager.prototype.serialize = function (name) {
  46339. var root = {
  46340. children: new Array(),
  46341. name: name,
  46342. type: 3,
  46343. properties: new Array() // Empty for root but required
  46344. };
  46345. for (var i = 0; i < this.actions.length; i++) {
  46346. var triggerObject = {
  46347. type: 0,
  46348. children: new Array(),
  46349. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46350. properties: new Array()
  46351. };
  46352. var triggerOptions = this.actions[i].triggerOptions;
  46353. if (triggerOptions && typeof triggerOptions !== "number") {
  46354. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46355. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46356. }
  46357. else {
  46358. var parameter = {};
  46359. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46360. if (triggerOptions.parameter.mesh) {
  46361. parameter._meshId = triggerOptions.parameter.mesh.id;
  46362. }
  46363. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46364. }
  46365. }
  46366. // Serialize child action, recursively
  46367. this.actions[i].serialize(triggerObject);
  46368. // Add serialized trigger
  46369. root.children.push(triggerObject);
  46370. }
  46371. return root;
  46372. };
  46373. ActionManager.Parse = function (parsedActions, object, scene) {
  46374. var actionManager = new ActionManager(scene);
  46375. if (object === null)
  46376. scene.actionManager = actionManager;
  46377. else
  46378. object.actionManager = actionManager;
  46379. // instanciate a new object
  46380. var instanciate = function (name, params) {
  46381. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46382. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46383. newInstance.constructor.apply(newInstance, params);
  46384. return newInstance;
  46385. };
  46386. var parseParameter = function (name, value, target, propertyPath) {
  46387. if (propertyPath === null) {
  46388. // String, boolean or float
  46389. var floatValue = parseFloat(value);
  46390. if (value === "true" || value === "false")
  46391. return value === "true";
  46392. else
  46393. return isNaN(floatValue) ? value : floatValue;
  46394. }
  46395. var effectiveTarget = propertyPath.split(".");
  46396. var values = value.split(",");
  46397. // Get effective Target
  46398. for (var i = 0; i < effectiveTarget.length; i++) {
  46399. target = target[effectiveTarget[i]];
  46400. }
  46401. // Return appropriate value with its type
  46402. if (typeof (target) === "boolean")
  46403. return values[0] === "true";
  46404. if (typeof (target) === "string")
  46405. return values[0];
  46406. // Parameters with multiple values such as Vector3 etc.
  46407. var split = new Array();
  46408. for (var i = 0; i < values.length; i++)
  46409. split.push(parseFloat(values[i]));
  46410. if (target instanceof BABYLON.Vector3)
  46411. return BABYLON.Vector3.FromArray(split);
  46412. if (target instanceof BABYLON.Vector4)
  46413. return BABYLON.Vector4.FromArray(split);
  46414. if (target instanceof BABYLON.Color3)
  46415. return BABYLON.Color3.FromArray(split);
  46416. if (target instanceof BABYLON.Color4)
  46417. return BABYLON.Color4.FromArray(split);
  46418. return parseFloat(values[0]);
  46419. };
  46420. // traverse graph per trigger
  46421. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46422. if (combineArray === void 0) { combineArray = null; }
  46423. if (parsedAction.detached)
  46424. return;
  46425. var parameters = new Array();
  46426. var target = null;
  46427. var propertyPath = null;
  46428. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46429. // Parameters
  46430. if (parsedAction.type === 2)
  46431. parameters.push(actionManager);
  46432. else
  46433. parameters.push(trigger);
  46434. if (combine) {
  46435. var actions = new Array();
  46436. for (var j = 0; j < parsedAction.combine.length; j++) {
  46437. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46438. }
  46439. parameters.push(actions);
  46440. }
  46441. else {
  46442. for (var i = 0; i < parsedAction.properties.length; i++) {
  46443. var value = parsedAction.properties[i].value;
  46444. var name = parsedAction.properties[i].name;
  46445. var targetType = parsedAction.properties[i].targetType;
  46446. if (name === "target")
  46447. if (targetType !== null && targetType === "SceneProperties")
  46448. value = target = scene;
  46449. else
  46450. value = target = scene.getNodeByName(value);
  46451. else if (name === "parent")
  46452. value = scene.getNodeByName(value);
  46453. else if (name === "sound")
  46454. value = scene.getSoundByName(value);
  46455. else if (name !== "propertyPath") {
  46456. if (parsedAction.type === 2 && name === "operator")
  46457. value = BABYLON.ValueCondition[value];
  46458. else
  46459. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46460. }
  46461. else {
  46462. propertyPath = value;
  46463. }
  46464. parameters.push(value);
  46465. }
  46466. }
  46467. if (combineArray === null) {
  46468. parameters.push(condition);
  46469. }
  46470. else {
  46471. parameters.push(null);
  46472. }
  46473. // If interpolate value action
  46474. if (parsedAction.name === "InterpolateValueAction") {
  46475. var param = parameters[parameters.length - 2];
  46476. parameters[parameters.length - 1] = param;
  46477. parameters[parameters.length - 2] = condition;
  46478. }
  46479. // Action or condition(s) and not CombineAction
  46480. var newAction = instanciate(parsedAction.name, parameters);
  46481. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46482. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46483. if (action)
  46484. action.then(nothing);
  46485. else
  46486. actionManager.registerAction(nothing);
  46487. action = nothing;
  46488. }
  46489. if (combineArray === null) {
  46490. if (newAction instanceof BABYLON.Condition) {
  46491. condition = newAction;
  46492. newAction = action;
  46493. }
  46494. else {
  46495. condition = null;
  46496. if (action)
  46497. action.then(newAction);
  46498. else
  46499. actionManager.registerAction(newAction);
  46500. }
  46501. }
  46502. else {
  46503. combineArray.push(newAction);
  46504. }
  46505. for (var i = 0; i < parsedAction.children.length; i++)
  46506. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46507. };
  46508. // triggers
  46509. for (var i = 0; i < parsedActions.children.length; i++) {
  46510. var triggerParams;
  46511. var trigger = parsedActions.children[i];
  46512. if (trigger.properties.length > 0) {
  46513. var param = trigger.properties[0].value;
  46514. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46515. if (value._meshId) {
  46516. value.mesh = scene.getMeshByID(value._meshId);
  46517. }
  46518. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46519. }
  46520. else
  46521. triggerParams = ActionManager[trigger.name];
  46522. for (var j = 0; j < trigger.children.length; j++) {
  46523. if (!trigger.detached)
  46524. traverse(trigger.children[j], triggerParams, null, null);
  46525. }
  46526. }
  46527. };
  46528. ActionManager.GetTriggerName = function (trigger) {
  46529. switch (trigger) {
  46530. case 0: return "NothingTrigger";
  46531. case 1: return "OnPickTrigger";
  46532. case 2: return "OnLeftPickTrigger";
  46533. case 3: return "OnRightPickTrigger";
  46534. case 4: return "OnCenterPickTrigger";
  46535. case 5: return "OnPickDownTrigger";
  46536. case 6: return "OnPickUpTrigger";
  46537. case 7: return "OnLongPressTrigger";
  46538. case 8: return "OnPointerOverTrigger";
  46539. case 9: return "OnPointerOutTrigger";
  46540. case 10: return "OnEveryFrameTrigger";
  46541. case 11: return "OnIntersectionEnterTrigger";
  46542. case 12: return "OnIntersectionExitTrigger";
  46543. case 13: return "OnKeyDownTrigger";
  46544. case 14: return "OnKeyUpTrigger";
  46545. case 15: return "OnPickOutTrigger";
  46546. default: return "";
  46547. }
  46548. };
  46549. // Statics
  46550. ActionManager._NothingTrigger = 0;
  46551. ActionManager._OnPickTrigger = 1;
  46552. ActionManager._OnLeftPickTrigger = 2;
  46553. ActionManager._OnRightPickTrigger = 3;
  46554. ActionManager._OnCenterPickTrigger = 4;
  46555. ActionManager._OnPickDownTrigger = 5;
  46556. ActionManager._OnDoublePickTrigger = 6;
  46557. ActionManager._OnPickUpTrigger = 7;
  46558. ActionManager._OnLongPressTrigger = 8;
  46559. ActionManager._OnPointerOverTrigger = 9;
  46560. ActionManager._OnPointerOutTrigger = 10;
  46561. ActionManager._OnEveryFrameTrigger = 11;
  46562. ActionManager._OnIntersectionEnterTrigger = 12;
  46563. ActionManager._OnIntersectionExitTrigger = 13;
  46564. ActionManager._OnKeyDownTrigger = 14;
  46565. ActionManager._OnKeyUpTrigger = 15;
  46566. ActionManager._OnPickOutTrigger = 16;
  46567. ActionManager.Triggers = {};
  46568. return ActionManager;
  46569. }());
  46570. BABYLON.ActionManager = ActionManager;
  46571. })(BABYLON || (BABYLON = {}));
  46572. //# sourceMappingURL=babylon.actionManager.js.map
  46573. var BABYLON;
  46574. (function (BABYLON) {
  46575. var InterpolateValueAction = /** @class */ (function (_super) {
  46576. __extends(InterpolateValueAction, _super);
  46577. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46578. if (duration === void 0) { duration = 1000; }
  46579. var _this = _super.call(this, triggerOptions, condition) || this;
  46580. _this.propertyPath = propertyPath;
  46581. _this.value = value;
  46582. _this.duration = duration;
  46583. _this.stopOtherAnimations = stopOtherAnimations;
  46584. _this.onInterpolationDone = onInterpolationDone;
  46585. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46586. _this._target = _this._effectiveTarget = target;
  46587. return _this;
  46588. }
  46589. InterpolateValueAction.prototype._prepare = function () {
  46590. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46591. this._property = this._getProperty(this.propertyPath);
  46592. };
  46593. InterpolateValueAction.prototype.execute = function () {
  46594. var _this = this;
  46595. var scene = this._actionManager.getScene();
  46596. var keys = [
  46597. {
  46598. frame: 0,
  46599. value: this._effectiveTarget[this._property]
  46600. }, {
  46601. frame: 100,
  46602. value: this.value
  46603. }
  46604. ];
  46605. var dataType;
  46606. if (typeof this.value === "number") {
  46607. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46608. }
  46609. else if (this.value instanceof BABYLON.Color3) {
  46610. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46611. }
  46612. else if (this.value instanceof BABYLON.Vector3) {
  46613. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46614. }
  46615. else if (this.value instanceof BABYLON.Matrix) {
  46616. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46617. }
  46618. else if (this.value instanceof BABYLON.Quaternion) {
  46619. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46620. }
  46621. else {
  46622. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46623. return;
  46624. }
  46625. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46626. animation.setKeys(keys);
  46627. if (this.stopOtherAnimations) {
  46628. scene.stopAnimation(this._effectiveTarget);
  46629. }
  46630. var wrapper = function () {
  46631. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46632. if (_this.onInterpolationDone) {
  46633. _this.onInterpolationDone();
  46634. }
  46635. };
  46636. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46637. };
  46638. InterpolateValueAction.prototype.serialize = function (parent) {
  46639. return _super.prototype._serialize.call(this, {
  46640. name: "InterpolateValueAction",
  46641. properties: [
  46642. BABYLON.Action._GetTargetProperty(this._target),
  46643. { name: "propertyPath", value: this.propertyPath },
  46644. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46645. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46646. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46647. ]
  46648. }, parent);
  46649. };
  46650. return InterpolateValueAction;
  46651. }(BABYLON.Action));
  46652. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46653. })(BABYLON || (BABYLON = {}));
  46654. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46655. var BABYLON;
  46656. (function (BABYLON) {
  46657. var SwitchBooleanAction = /** @class */ (function (_super) {
  46658. __extends(SwitchBooleanAction, _super);
  46659. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46660. var _this = _super.call(this, triggerOptions, condition) || this;
  46661. _this.propertyPath = propertyPath;
  46662. _this._target = _this._effectiveTarget = target;
  46663. return _this;
  46664. }
  46665. SwitchBooleanAction.prototype._prepare = function () {
  46666. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46667. this._property = this._getProperty(this.propertyPath);
  46668. };
  46669. SwitchBooleanAction.prototype.execute = function () {
  46670. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46671. };
  46672. SwitchBooleanAction.prototype.serialize = function (parent) {
  46673. return _super.prototype._serialize.call(this, {
  46674. name: "SwitchBooleanAction",
  46675. properties: [
  46676. BABYLON.Action._GetTargetProperty(this._target),
  46677. { name: "propertyPath", value: this.propertyPath }
  46678. ]
  46679. }, parent);
  46680. };
  46681. return SwitchBooleanAction;
  46682. }(BABYLON.Action));
  46683. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46684. var SetStateAction = /** @class */ (function (_super) {
  46685. __extends(SetStateAction, _super);
  46686. function SetStateAction(triggerOptions, target, value, condition) {
  46687. var _this = _super.call(this, triggerOptions, condition) || this;
  46688. _this.value = value;
  46689. _this._target = target;
  46690. return _this;
  46691. }
  46692. SetStateAction.prototype.execute = function () {
  46693. this._target.state = this.value;
  46694. };
  46695. SetStateAction.prototype.serialize = function (parent) {
  46696. return _super.prototype._serialize.call(this, {
  46697. name: "SetStateAction",
  46698. properties: [
  46699. BABYLON.Action._GetTargetProperty(this._target),
  46700. { name: "value", value: this.value }
  46701. ]
  46702. }, parent);
  46703. };
  46704. return SetStateAction;
  46705. }(BABYLON.Action));
  46706. BABYLON.SetStateAction = SetStateAction;
  46707. var SetValueAction = /** @class */ (function (_super) {
  46708. __extends(SetValueAction, _super);
  46709. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46710. var _this = _super.call(this, triggerOptions, condition) || this;
  46711. _this.propertyPath = propertyPath;
  46712. _this.value = value;
  46713. _this._target = _this._effectiveTarget = target;
  46714. return _this;
  46715. }
  46716. SetValueAction.prototype._prepare = function () {
  46717. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46718. this._property = this._getProperty(this.propertyPath);
  46719. };
  46720. SetValueAction.prototype.execute = function () {
  46721. this._effectiveTarget[this._property] = this.value;
  46722. if (this._target.markAsDirty) {
  46723. this._target.markAsDirty(this._property);
  46724. }
  46725. };
  46726. SetValueAction.prototype.serialize = function (parent) {
  46727. return _super.prototype._serialize.call(this, {
  46728. name: "SetValueAction",
  46729. properties: [
  46730. BABYLON.Action._GetTargetProperty(this._target),
  46731. { name: "propertyPath", value: this.propertyPath },
  46732. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46733. ]
  46734. }, parent);
  46735. };
  46736. return SetValueAction;
  46737. }(BABYLON.Action));
  46738. BABYLON.SetValueAction = SetValueAction;
  46739. var IncrementValueAction = /** @class */ (function (_super) {
  46740. __extends(IncrementValueAction, _super);
  46741. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46742. var _this = _super.call(this, triggerOptions, condition) || this;
  46743. _this.propertyPath = propertyPath;
  46744. _this.value = value;
  46745. _this._target = _this._effectiveTarget = target;
  46746. return _this;
  46747. }
  46748. IncrementValueAction.prototype._prepare = function () {
  46749. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46750. this._property = this._getProperty(this.propertyPath);
  46751. if (typeof this._effectiveTarget[this._property] !== "number") {
  46752. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46753. }
  46754. };
  46755. IncrementValueAction.prototype.execute = function () {
  46756. this._effectiveTarget[this._property] += this.value;
  46757. if (this._target.markAsDirty) {
  46758. this._target.markAsDirty(this._property);
  46759. }
  46760. };
  46761. IncrementValueAction.prototype.serialize = function (parent) {
  46762. return _super.prototype._serialize.call(this, {
  46763. name: "IncrementValueAction",
  46764. properties: [
  46765. BABYLON.Action._GetTargetProperty(this._target),
  46766. { name: "propertyPath", value: this.propertyPath },
  46767. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46768. ]
  46769. }, parent);
  46770. };
  46771. return IncrementValueAction;
  46772. }(BABYLON.Action));
  46773. BABYLON.IncrementValueAction = IncrementValueAction;
  46774. var PlayAnimationAction = /** @class */ (function (_super) {
  46775. __extends(PlayAnimationAction, _super);
  46776. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46777. var _this = _super.call(this, triggerOptions, condition) || this;
  46778. _this.from = from;
  46779. _this.to = to;
  46780. _this.loop = loop;
  46781. _this._target = target;
  46782. return _this;
  46783. }
  46784. PlayAnimationAction.prototype._prepare = function () {
  46785. };
  46786. PlayAnimationAction.prototype.execute = function () {
  46787. var scene = this._actionManager.getScene();
  46788. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46789. };
  46790. PlayAnimationAction.prototype.serialize = function (parent) {
  46791. return _super.prototype._serialize.call(this, {
  46792. name: "PlayAnimationAction",
  46793. properties: [
  46794. BABYLON.Action._GetTargetProperty(this._target),
  46795. { name: "from", value: String(this.from) },
  46796. { name: "to", value: String(this.to) },
  46797. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46798. ]
  46799. }, parent);
  46800. };
  46801. return PlayAnimationAction;
  46802. }(BABYLON.Action));
  46803. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46804. var StopAnimationAction = /** @class */ (function (_super) {
  46805. __extends(StopAnimationAction, _super);
  46806. function StopAnimationAction(triggerOptions, target, condition) {
  46807. var _this = _super.call(this, triggerOptions, condition) || this;
  46808. _this._target = target;
  46809. return _this;
  46810. }
  46811. StopAnimationAction.prototype._prepare = function () {
  46812. };
  46813. StopAnimationAction.prototype.execute = function () {
  46814. var scene = this._actionManager.getScene();
  46815. scene.stopAnimation(this._target);
  46816. };
  46817. StopAnimationAction.prototype.serialize = function (parent) {
  46818. return _super.prototype._serialize.call(this, {
  46819. name: "StopAnimationAction",
  46820. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46821. }, parent);
  46822. };
  46823. return StopAnimationAction;
  46824. }(BABYLON.Action));
  46825. BABYLON.StopAnimationAction = StopAnimationAction;
  46826. var DoNothingAction = /** @class */ (function (_super) {
  46827. __extends(DoNothingAction, _super);
  46828. function DoNothingAction(triggerOptions, condition) {
  46829. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46830. return _super.call(this, triggerOptions, condition) || this;
  46831. }
  46832. DoNothingAction.prototype.execute = function () {
  46833. };
  46834. DoNothingAction.prototype.serialize = function (parent) {
  46835. return _super.prototype._serialize.call(this, {
  46836. name: "DoNothingAction",
  46837. properties: []
  46838. }, parent);
  46839. };
  46840. return DoNothingAction;
  46841. }(BABYLON.Action));
  46842. BABYLON.DoNothingAction = DoNothingAction;
  46843. var CombineAction = /** @class */ (function (_super) {
  46844. __extends(CombineAction, _super);
  46845. function CombineAction(triggerOptions, children, condition) {
  46846. var _this = _super.call(this, triggerOptions, condition) || this;
  46847. _this.children = children;
  46848. return _this;
  46849. }
  46850. CombineAction.prototype._prepare = function () {
  46851. for (var index = 0; index < this.children.length; index++) {
  46852. this.children[index]._actionManager = this._actionManager;
  46853. this.children[index]._prepare();
  46854. }
  46855. };
  46856. CombineAction.prototype.execute = function (evt) {
  46857. for (var index = 0; index < this.children.length; index++) {
  46858. this.children[index].execute(evt);
  46859. }
  46860. };
  46861. CombineAction.prototype.serialize = function (parent) {
  46862. var serializationObject = _super.prototype._serialize.call(this, {
  46863. name: "CombineAction",
  46864. properties: [],
  46865. combine: []
  46866. }, parent);
  46867. for (var i = 0; i < this.children.length; i++) {
  46868. serializationObject.combine.push(this.children[i].serialize(null));
  46869. }
  46870. return serializationObject;
  46871. };
  46872. return CombineAction;
  46873. }(BABYLON.Action));
  46874. BABYLON.CombineAction = CombineAction;
  46875. var ExecuteCodeAction = /** @class */ (function (_super) {
  46876. __extends(ExecuteCodeAction, _super);
  46877. function ExecuteCodeAction(triggerOptions, func, condition) {
  46878. var _this = _super.call(this, triggerOptions, condition) || this;
  46879. _this.func = func;
  46880. return _this;
  46881. }
  46882. ExecuteCodeAction.prototype.execute = function (evt) {
  46883. this.func(evt);
  46884. };
  46885. return ExecuteCodeAction;
  46886. }(BABYLON.Action));
  46887. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46888. var SetParentAction = /** @class */ (function (_super) {
  46889. __extends(SetParentAction, _super);
  46890. function SetParentAction(triggerOptions, target, parent, condition) {
  46891. var _this = _super.call(this, triggerOptions, condition) || this;
  46892. _this._target = target;
  46893. _this._parent = parent;
  46894. return _this;
  46895. }
  46896. SetParentAction.prototype._prepare = function () {
  46897. };
  46898. SetParentAction.prototype.execute = function () {
  46899. if (this._target.parent === this._parent) {
  46900. return;
  46901. }
  46902. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46903. invertParentWorldMatrix.invert();
  46904. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46905. this._target.parent = this._parent;
  46906. };
  46907. SetParentAction.prototype.serialize = function (parent) {
  46908. return _super.prototype._serialize.call(this, {
  46909. name: "SetParentAction",
  46910. properties: [
  46911. BABYLON.Action._GetTargetProperty(this._target),
  46912. BABYLON.Action._GetTargetProperty(this._parent),
  46913. ]
  46914. }, parent);
  46915. };
  46916. return SetParentAction;
  46917. }(BABYLON.Action));
  46918. BABYLON.SetParentAction = SetParentAction;
  46919. var PlaySoundAction = /** @class */ (function (_super) {
  46920. __extends(PlaySoundAction, _super);
  46921. function PlaySoundAction(triggerOptions, sound, condition) {
  46922. var _this = _super.call(this, triggerOptions, condition) || this;
  46923. _this._sound = sound;
  46924. return _this;
  46925. }
  46926. PlaySoundAction.prototype._prepare = function () {
  46927. };
  46928. PlaySoundAction.prototype.execute = function () {
  46929. if (this._sound !== undefined)
  46930. this._sound.play();
  46931. };
  46932. PlaySoundAction.prototype.serialize = function (parent) {
  46933. return _super.prototype._serialize.call(this, {
  46934. name: "PlaySoundAction",
  46935. properties: [{ name: "sound", value: this._sound.name }]
  46936. }, parent);
  46937. };
  46938. return PlaySoundAction;
  46939. }(BABYLON.Action));
  46940. BABYLON.PlaySoundAction = PlaySoundAction;
  46941. var StopSoundAction = /** @class */ (function (_super) {
  46942. __extends(StopSoundAction, _super);
  46943. function StopSoundAction(triggerOptions, sound, condition) {
  46944. var _this = _super.call(this, triggerOptions, condition) || this;
  46945. _this._sound = sound;
  46946. return _this;
  46947. }
  46948. StopSoundAction.prototype._prepare = function () {
  46949. };
  46950. StopSoundAction.prototype.execute = function () {
  46951. if (this._sound !== undefined)
  46952. this._sound.stop();
  46953. };
  46954. StopSoundAction.prototype.serialize = function (parent) {
  46955. return _super.prototype._serialize.call(this, {
  46956. name: "StopSoundAction",
  46957. properties: [{ name: "sound", value: this._sound.name }]
  46958. }, parent);
  46959. };
  46960. return StopSoundAction;
  46961. }(BABYLON.Action));
  46962. BABYLON.StopSoundAction = StopSoundAction;
  46963. })(BABYLON || (BABYLON = {}));
  46964. //# sourceMappingURL=babylon.directActions.js.map
  46965. var BABYLON;
  46966. (function (BABYLON) {
  46967. var SpriteManager = /** @class */ (function () {
  46968. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46969. if (epsilon === void 0) { epsilon = 0.01; }
  46970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46971. this.name = name;
  46972. this.sprites = new Array();
  46973. this.renderingGroupId = 0;
  46974. this.layerMask = 0x0FFFFFFF;
  46975. this.fogEnabled = true;
  46976. this.isPickable = false;
  46977. /**
  46978. * An event triggered when the manager is disposed.
  46979. * @type {BABYLON.Observable}
  46980. */
  46981. this.onDisposeObservable = new BABYLON.Observable();
  46982. this._vertexBuffers = {};
  46983. this._capacity = capacity;
  46984. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46985. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46986. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46987. if (cellSize.width && cellSize.height) {
  46988. this.cellWidth = cellSize.width;
  46989. this.cellHeight = cellSize.height;
  46990. }
  46991. else if (cellSize !== undefined) {
  46992. this.cellWidth = cellSize;
  46993. this.cellHeight = cellSize;
  46994. }
  46995. else {
  46996. return;
  46997. }
  46998. this._epsilon = epsilon;
  46999. this._scene = scene;
  47000. this._scene.spriteManagers.push(this);
  47001. var indices = [];
  47002. var index = 0;
  47003. for (var count = 0; count < capacity; count++) {
  47004. indices.push(index);
  47005. indices.push(index + 1);
  47006. indices.push(index + 2);
  47007. indices.push(index);
  47008. indices.push(index + 2);
  47009. indices.push(index + 3);
  47010. index += 4;
  47011. }
  47012. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  47013. // VBO
  47014. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  47015. this._vertexData = new Float32Array(capacity * 16 * 4);
  47016. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  47017. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  47018. var options = this._buffer.createVertexBuffer("options", 4, 4);
  47019. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  47020. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  47021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47022. this._vertexBuffers["options"] = options;
  47023. this._vertexBuffers["cellInfo"] = cellInfo;
  47024. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47025. // Effects
  47026. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  47027. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  47028. }
  47029. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  47030. set: function (callback) {
  47031. if (this._onDisposeObserver) {
  47032. this.onDisposeObservable.remove(this._onDisposeObserver);
  47033. }
  47034. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47035. },
  47036. enumerable: true,
  47037. configurable: true
  47038. });
  47039. Object.defineProperty(SpriteManager.prototype, "texture", {
  47040. get: function () {
  47041. return this._spriteTexture;
  47042. },
  47043. set: function (value) {
  47044. this._spriteTexture = value;
  47045. },
  47046. enumerable: true,
  47047. configurable: true
  47048. });
  47049. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  47050. var arrayOffset = index * 16;
  47051. if (offsetX === 0)
  47052. offsetX = this._epsilon;
  47053. else if (offsetX === 1)
  47054. offsetX = 1 - this._epsilon;
  47055. if (offsetY === 0)
  47056. offsetY = this._epsilon;
  47057. else if (offsetY === 1)
  47058. offsetY = 1 - this._epsilon;
  47059. this._vertexData[arrayOffset] = sprite.position.x;
  47060. this._vertexData[arrayOffset + 1] = sprite.position.y;
  47061. this._vertexData[arrayOffset + 2] = sprite.position.z;
  47062. this._vertexData[arrayOffset + 3] = sprite.angle;
  47063. this._vertexData[arrayOffset + 4] = sprite.width;
  47064. this._vertexData[arrayOffset + 5] = sprite.height;
  47065. this._vertexData[arrayOffset + 6] = offsetX;
  47066. this._vertexData[arrayOffset + 7] = offsetY;
  47067. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  47068. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  47069. var offset = (sprite.cellIndex / rowSize) >> 0;
  47070. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  47071. this._vertexData[arrayOffset + 11] = offset;
  47072. // Color
  47073. this._vertexData[arrayOffset + 12] = sprite.color.r;
  47074. this._vertexData[arrayOffset + 13] = sprite.color.g;
  47075. this._vertexData[arrayOffset + 14] = sprite.color.b;
  47076. this._vertexData[arrayOffset + 15] = sprite.color.a;
  47077. };
  47078. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  47079. var count = Math.min(this._capacity, this.sprites.length);
  47080. var min = BABYLON.Vector3.Zero();
  47081. var max = BABYLON.Vector3.Zero();
  47082. var distance = Number.MAX_VALUE;
  47083. var currentSprite = null;
  47084. var cameraSpacePosition = BABYLON.Vector3.Zero();
  47085. var cameraView = camera.getViewMatrix();
  47086. for (var index = 0; index < count; index++) {
  47087. var sprite = this.sprites[index];
  47088. if (!sprite) {
  47089. continue;
  47090. }
  47091. if (predicate) {
  47092. if (!predicate(sprite)) {
  47093. continue;
  47094. }
  47095. }
  47096. else if (!sprite.isPickable) {
  47097. continue;
  47098. }
  47099. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  47100. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  47101. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  47102. if (ray.intersectsBoxMinMax(min, max)) {
  47103. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  47104. if (distance > currentDistance) {
  47105. distance = currentDistance;
  47106. currentSprite = sprite;
  47107. if (fastCheck) {
  47108. break;
  47109. }
  47110. }
  47111. }
  47112. }
  47113. if (currentSprite) {
  47114. var result = new BABYLON.PickingInfo();
  47115. result.hit = true;
  47116. result.pickedSprite = currentSprite;
  47117. result.distance = distance;
  47118. return result;
  47119. }
  47120. return null;
  47121. };
  47122. SpriteManager.prototype.render = function () {
  47123. // Check
  47124. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  47125. return;
  47126. var engine = this._scene.getEngine();
  47127. var baseSize = this._spriteTexture.getBaseSize();
  47128. // Sprites
  47129. var deltaTime = engine.getDeltaTime();
  47130. var max = Math.min(this._capacity, this.sprites.length);
  47131. var rowSize = baseSize.width / this.cellWidth;
  47132. var offset = 0;
  47133. for (var index = 0; index < max; index++) {
  47134. var sprite = this.sprites[index];
  47135. if (!sprite) {
  47136. continue;
  47137. }
  47138. sprite._animate(deltaTime);
  47139. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  47140. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  47141. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  47142. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  47143. }
  47144. this._buffer.update(this._vertexData);
  47145. // Render
  47146. var effect = this._effectBase;
  47147. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  47148. effect = this._effectFog;
  47149. }
  47150. engine.enableEffect(effect);
  47151. var viewMatrix = this._scene.getViewMatrix();
  47152. effect.setTexture("diffuseSampler", this._spriteTexture);
  47153. effect.setMatrix("view", viewMatrix);
  47154. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47155. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  47156. // Fog
  47157. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  47158. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  47159. effect.setColor3("vFogColor", this._scene.fogColor);
  47160. }
  47161. // VBOs
  47162. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47163. // Draw order
  47164. engine.setDepthFunctionToLessOrEqual();
  47165. effect.setBool("alphaTest", true);
  47166. engine.setColorWrite(false);
  47167. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  47168. engine.setColorWrite(true);
  47169. effect.setBool("alphaTest", false);
  47170. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47171. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  47172. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47173. };
  47174. SpriteManager.prototype.dispose = function () {
  47175. if (this._buffer) {
  47176. this._buffer.dispose();
  47177. this._buffer = null;
  47178. }
  47179. if (this._indexBuffer) {
  47180. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47181. this._indexBuffer = null;
  47182. }
  47183. if (this._spriteTexture) {
  47184. this._spriteTexture.dispose();
  47185. this._spriteTexture = null;
  47186. }
  47187. // Remove from scene
  47188. var index = this._scene.spriteManagers.indexOf(this);
  47189. this._scene.spriteManagers.splice(index, 1);
  47190. // Callback
  47191. this.onDisposeObservable.notifyObservers(this);
  47192. this.onDisposeObservable.clear();
  47193. };
  47194. return SpriteManager;
  47195. }());
  47196. BABYLON.SpriteManager = SpriteManager;
  47197. })(BABYLON || (BABYLON = {}));
  47198. //# sourceMappingURL=babylon.spriteManager.js.map
  47199. var BABYLON;
  47200. (function (BABYLON) {
  47201. var Sprite = /** @class */ (function () {
  47202. function Sprite(name, manager) {
  47203. this.name = name;
  47204. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47205. this.width = 1.0;
  47206. this.height = 1.0;
  47207. this.angle = 0;
  47208. this.cellIndex = 0;
  47209. this.invertU = 0;
  47210. this.invertV = 0;
  47211. this.animations = new Array();
  47212. this.isPickable = false;
  47213. this._animationStarted = false;
  47214. this._loopAnimation = false;
  47215. this._fromIndex = 0;
  47216. this._toIndex = 0;
  47217. this._delay = 0;
  47218. this._direction = 1;
  47219. this._time = 0;
  47220. this._manager = manager;
  47221. this._manager.sprites.push(this);
  47222. this.position = BABYLON.Vector3.Zero();
  47223. }
  47224. Object.defineProperty(Sprite.prototype, "size", {
  47225. get: function () {
  47226. return this.width;
  47227. },
  47228. set: function (value) {
  47229. this.width = value;
  47230. this.height = value;
  47231. },
  47232. enumerable: true,
  47233. configurable: true
  47234. });
  47235. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  47236. this._fromIndex = from;
  47237. this._toIndex = to;
  47238. this._loopAnimation = loop;
  47239. this._delay = delay;
  47240. this._animationStarted = true;
  47241. this._direction = from < to ? 1 : -1;
  47242. this.cellIndex = from;
  47243. this._time = 0;
  47244. this._onAnimationEnd = onAnimationEnd;
  47245. };
  47246. Sprite.prototype.stopAnimation = function () {
  47247. this._animationStarted = false;
  47248. };
  47249. Sprite.prototype._animate = function (deltaTime) {
  47250. if (!this._animationStarted)
  47251. return;
  47252. this._time += deltaTime;
  47253. if (this._time > this._delay) {
  47254. this._time = this._time % this._delay;
  47255. this.cellIndex += this._direction;
  47256. if (this.cellIndex > this._toIndex) {
  47257. if (this._loopAnimation) {
  47258. this.cellIndex = this._fromIndex;
  47259. }
  47260. else {
  47261. this.cellIndex = this._toIndex;
  47262. this._animationStarted = false;
  47263. if (this._onAnimationEnd) {
  47264. this._onAnimationEnd();
  47265. }
  47266. if (this.disposeWhenFinishedAnimating) {
  47267. this.dispose();
  47268. }
  47269. }
  47270. }
  47271. }
  47272. };
  47273. Sprite.prototype.dispose = function () {
  47274. for (var i = 0; i < this._manager.sprites.length; i++) {
  47275. if (this._manager.sprites[i] == this) {
  47276. this._manager.sprites.splice(i, 1);
  47277. }
  47278. }
  47279. };
  47280. return Sprite;
  47281. }());
  47282. BABYLON.Sprite = Sprite;
  47283. })(BABYLON || (BABYLON = {}));
  47284. //# sourceMappingURL=babylon.sprite.js.map
  47285. var BABYLON;
  47286. (function (BABYLON) {
  47287. var IntersectionInfo = /** @class */ (function () {
  47288. function IntersectionInfo(bu, bv, distance) {
  47289. this.bu = bu;
  47290. this.bv = bv;
  47291. this.distance = distance;
  47292. this.faceId = 0;
  47293. this.subMeshId = 0;
  47294. }
  47295. return IntersectionInfo;
  47296. }());
  47297. BABYLON.IntersectionInfo = IntersectionInfo;
  47298. var PickingInfo = /** @class */ (function () {
  47299. function PickingInfo() {
  47300. this.hit = false;
  47301. this.distance = 0;
  47302. this.pickedPoint = null;
  47303. this.pickedMesh = null;
  47304. this.bu = 0;
  47305. this.bv = 0;
  47306. this.faceId = -1;
  47307. this.subMeshId = 0;
  47308. this.pickedSprite = null;
  47309. }
  47310. // Methods
  47311. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47312. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47313. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47314. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47315. return null;
  47316. }
  47317. var indices = this.pickedMesh.getIndices();
  47318. if (!indices) {
  47319. return null;
  47320. }
  47321. var result;
  47322. if (useVerticesNormals) {
  47323. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47324. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47325. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47326. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47327. normal0 = normal0.scale(this.bu);
  47328. normal1 = normal1.scale(this.bv);
  47329. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47330. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47331. }
  47332. else {
  47333. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47334. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47335. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47336. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47337. var p1p2 = vertex1.subtract(vertex2);
  47338. var p3p2 = vertex3.subtract(vertex2);
  47339. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47340. }
  47341. if (useWorldCoordinates) {
  47342. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47343. }
  47344. return BABYLON.Vector3.Normalize(result);
  47345. };
  47346. PickingInfo.prototype.getTextureCoordinates = function () {
  47347. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47348. return null;
  47349. }
  47350. var indices = this.pickedMesh.getIndices();
  47351. if (!indices) {
  47352. return null;
  47353. }
  47354. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47355. if (!uvs) {
  47356. return null;
  47357. }
  47358. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47359. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47360. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47361. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47362. uv1 = uv1.scale(this.bu);
  47363. uv2 = uv2.scale(this.bv);
  47364. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47365. };
  47366. return PickingInfo;
  47367. }());
  47368. BABYLON.PickingInfo = PickingInfo;
  47369. })(BABYLON || (BABYLON = {}));
  47370. //# sourceMappingURL=babylon.pickingInfo.js.map
  47371. var BABYLON;
  47372. (function (BABYLON) {
  47373. var Ray = /** @class */ (function () {
  47374. function Ray(origin, direction, length) {
  47375. if (length === void 0) { length = Number.MAX_VALUE; }
  47376. this.origin = origin;
  47377. this.direction = direction;
  47378. this.length = length;
  47379. }
  47380. // Methods
  47381. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47382. var d = 0.0;
  47383. var maxValue = Number.MAX_VALUE;
  47384. var inv;
  47385. var min;
  47386. var max;
  47387. var temp;
  47388. if (Math.abs(this.direction.x) < 0.0000001) {
  47389. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47390. return false;
  47391. }
  47392. }
  47393. else {
  47394. inv = 1.0 / this.direction.x;
  47395. min = (minimum.x - this.origin.x) * inv;
  47396. max = (maximum.x - this.origin.x) * inv;
  47397. if (max === -Infinity) {
  47398. max = Infinity;
  47399. }
  47400. if (min > max) {
  47401. temp = min;
  47402. min = max;
  47403. max = temp;
  47404. }
  47405. d = Math.max(min, d);
  47406. maxValue = Math.min(max, maxValue);
  47407. if (d > maxValue) {
  47408. return false;
  47409. }
  47410. }
  47411. if (Math.abs(this.direction.y) < 0.0000001) {
  47412. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47413. return false;
  47414. }
  47415. }
  47416. else {
  47417. inv = 1.0 / this.direction.y;
  47418. min = (minimum.y - this.origin.y) * inv;
  47419. max = (maximum.y - this.origin.y) * inv;
  47420. if (max === -Infinity) {
  47421. max = Infinity;
  47422. }
  47423. if (min > max) {
  47424. temp = min;
  47425. min = max;
  47426. max = temp;
  47427. }
  47428. d = Math.max(min, d);
  47429. maxValue = Math.min(max, maxValue);
  47430. if (d > maxValue) {
  47431. return false;
  47432. }
  47433. }
  47434. if (Math.abs(this.direction.z) < 0.0000001) {
  47435. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47436. return false;
  47437. }
  47438. }
  47439. else {
  47440. inv = 1.0 / this.direction.z;
  47441. min = (minimum.z - this.origin.z) * inv;
  47442. max = (maximum.z - this.origin.z) * inv;
  47443. if (max === -Infinity) {
  47444. max = Infinity;
  47445. }
  47446. if (min > max) {
  47447. temp = min;
  47448. min = max;
  47449. max = temp;
  47450. }
  47451. d = Math.max(min, d);
  47452. maxValue = Math.min(max, maxValue);
  47453. if (d > maxValue) {
  47454. return false;
  47455. }
  47456. }
  47457. return true;
  47458. };
  47459. Ray.prototype.intersectsBox = function (box) {
  47460. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47461. };
  47462. Ray.prototype.intersectsSphere = function (sphere) {
  47463. var x = sphere.center.x - this.origin.x;
  47464. var y = sphere.center.y - this.origin.y;
  47465. var z = sphere.center.z - this.origin.z;
  47466. var pyth = (x * x) + (y * y) + (z * z);
  47467. var rr = sphere.radius * sphere.radius;
  47468. if (pyth <= rr) {
  47469. return true;
  47470. }
  47471. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47472. if (dot < 0.0) {
  47473. return false;
  47474. }
  47475. var temp = pyth - (dot * dot);
  47476. return temp <= rr;
  47477. };
  47478. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47479. if (!this._edge1) {
  47480. this._edge1 = BABYLON.Vector3.Zero();
  47481. this._edge2 = BABYLON.Vector3.Zero();
  47482. this._pvec = BABYLON.Vector3.Zero();
  47483. this._tvec = BABYLON.Vector3.Zero();
  47484. this._qvec = BABYLON.Vector3.Zero();
  47485. }
  47486. vertex1.subtractToRef(vertex0, this._edge1);
  47487. vertex2.subtractToRef(vertex0, this._edge2);
  47488. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47489. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47490. if (det === 0) {
  47491. return null;
  47492. }
  47493. var invdet = 1 / det;
  47494. this.origin.subtractToRef(vertex0, this._tvec);
  47495. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47496. if (bu < 0 || bu > 1.0) {
  47497. return null;
  47498. }
  47499. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47500. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47501. if (bv < 0 || bu + bv > 1.0) {
  47502. return null;
  47503. }
  47504. //check if the distance is longer than the predefined length.
  47505. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47506. if (distance > this.length) {
  47507. return null;
  47508. }
  47509. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47510. };
  47511. Ray.prototype.intersectsPlane = function (plane) {
  47512. var distance;
  47513. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47514. if (Math.abs(result1) < 9.99999997475243E-07) {
  47515. return null;
  47516. }
  47517. else {
  47518. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47519. distance = (-plane.d - result2) / result1;
  47520. if (distance < 0.0) {
  47521. if (distance < -9.99999997475243E-07) {
  47522. return null;
  47523. }
  47524. else {
  47525. return 0;
  47526. }
  47527. }
  47528. return distance;
  47529. }
  47530. };
  47531. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47532. var tm = BABYLON.Tmp.Matrix[0];
  47533. mesh.getWorldMatrix().invertToRef(tm);
  47534. if (this._tmpRay) {
  47535. Ray.TransformToRef(this, tm, this._tmpRay);
  47536. }
  47537. else {
  47538. this._tmpRay = Ray.Transform(this, tm);
  47539. }
  47540. return mesh.intersects(this._tmpRay, fastCheck);
  47541. };
  47542. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47543. if (results) {
  47544. results.length = 0;
  47545. }
  47546. else {
  47547. results = [];
  47548. }
  47549. for (var i = 0; i < meshes.length; i++) {
  47550. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47551. if (pickInfo.hit) {
  47552. results.push(pickInfo);
  47553. }
  47554. }
  47555. results.sort(this._comparePickingInfo);
  47556. return results;
  47557. };
  47558. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47559. if (pickingInfoA.distance < pickingInfoB.distance) {
  47560. return -1;
  47561. }
  47562. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47563. return 1;
  47564. }
  47565. else {
  47566. return 0;
  47567. }
  47568. };
  47569. /**
  47570. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47571. * @param sega the first point of the segment to test the intersection against
  47572. * @param segb the second point of the segment to test the intersection against
  47573. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47574. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47575. */
  47576. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47577. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47578. var u = segb.subtract(sega);
  47579. var v = rsegb.subtract(this.origin);
  47580. var w = sega.subtract(this.origin);
  47581. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47582. var b = BABYLON.Vector3.Dot(u, v);
  47583. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47584. var d = BABYLON.Vector3.Dot(u, w);
  47585. var e = BABYLON.Vector3.Dot(v, w);
  47586. var D = a * c - b * b; // always >= 0
  47587. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47588. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47589. // compute the line parameters of the two closest points
  47590. if (D < Ray.smallnum) {
  47591. sN = 0.0; // force using point P0 on segment S1
  47592. sD = 1.0; // to prevent possible division by 0.0 later
  47593. tN = e;
  47594. tD = c;
  47595. }
  47596. else {
  47597. sN = (b * e - c * d);
  47598. tN = (a * e - b * d);
  47599. if (sN < 0.0) {
  47600. sN = 0.0;
  47601. tN = e;
  47602. tD = c;
  47603. }
  47604. else if (sN > sD) {
  47605. sN = sD;
  47606. tN = e + b;
  47607. tD = c;
  47608. }
  47609. }
  47610. if (tN < 0.0) {
  47611. tN = 0.0;
  47612. // recompute sc for this edge
  47613. if (-d < 0.0) {
  47614. sN = 0.0;
  47615. }
  47616. else if (-d > a)
  47617. sN = sD;
  47618. else {
  47619. sN = -d;
  47620. sD = a;
  47621. }
  47622. }
  47623. else if (tN > tD) {
  47624. tN = tD;
  47625. // recompute sc for this edge
  47626. if ((-d + b) < 0.0) {
  47627. sN = 0;
  47628. }
  47629. else if ((-d + b) > a) {
  47630. sN = sD;
  47631. }
  47632. else {
  47633. sN = (-d + b);
  47634. sD = a;
  47635. }
  47636. }
  47637. // finally do the division to get sc and tc
  47638. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47639. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47640. // get the difference of the two closest points
  47641. var qtc = v.multiplyByFloats(tc, tc, tc);
  47642. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47643. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47644. if (isIntersected) {
  47645. return qtc.length();
  47646. }
  47647. return -1;
  47648. };
  47649. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47650. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47651. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47652. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47653. this.direction.normalize();
  47654. return this;
  47655. };
  47656. // Statics
  47657. Ray.Zero = function () {
  47658. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47659. };
  47660. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47661. var result = Ray.Zero();
  47662. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47663. };
  47664. /**
  47665. * 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
  47666. * transformed to the given world matrix.
  47667. * @param origin The origin point
  47668. * @param end The end point
  47669. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47670. */
  47671. Ray.CreateNewFromTo = function (origin, end, world) {
  47672. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47673. var direction = end.subtract(origin);
  47674. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47675. direction.normalize();
  47676. return Ray.Transform(new Ray(origin, direction, length), world);
  47677. };
  47678. Ray.Transform = function (ray, matrix) {
  47679. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47680. Ray.TransformToRef(ray, matrix, result);
  47681. return result;
  47682. };
  47683. Ray.TransformToRef = function (ray, matrix, result) {
  47684. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47685. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47686. result.length = ray.length;
  47687. var dir = result.direction;
  47688. var len = dir.length();
  47689. if (!(len === 0 || len === 1)) {
  47690. var num = 1.0 / len;
  47691. dir.x *= num;
  47692. dir.y *= num;
  47693. dir.z *= num;
  47694. result.length *= len;
  47695. }
  47696. };
  47697. Ray.smallnum = 0.00000001;
  47698. Ray.rayl = 10e8;
  47699. return Ray;
  47700. }());
  47701. BABYLON.Ray = Ray;
  47702. })(BABYLON || (BABYLON = {}));
  47703. //# sourceMappingURL=babylon.ray.js.map
  47704. var BABYLON;
  47705. (function (BABYLON) {
  47706. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47707. if (boxMin.x > sphereCenter.x + sphereRadius)
  47708. return false;
  47709. if (sphereCenter.x - sphereRadius > boxMax.x)
  47710. return false;
  47711. if (boxMin.y > sphereCenter.y + sphereRadius)
  47712. return false;
  47713. if (sphereCenter.y - sphereRadius > boxMax.y)
  47714. return false;
  47715. if (boxMin.z > sphereCenter.z + sphereRadius)
  47716. return false;
  47717. if (sphereCenter.z - sphereRadius > boxMax.z)
  47718. return false;
  47719. return true;
  47720. };
  47721. var getLowestRoot = (function () {
  47722. var result = { root: 0, found: false };
  47723. return function (a, b, c, maxR) {
  47724. result.root = 0;
  47725. result.found = false;
  47726. var determinant = b * b - 4.0 * a * c;
  47727. if (determinant < 0)
  47728. return result;
  47729. var sqrtD = Math.sqrt(determinant);
  47730. var r1 = (-b - sqrtD) / (2.0 * a);
  47731. var r2 = (-b + sqrtD) / (2.0 * a);
  47732. if (r1 > r2) {
  47733. var temp = r2;
  47734. r2 = r1;
  47735. r1 = temp;
  47736. }
  47737. if (r1 > 0 && r1 < maxR) {
  47738. result.root = r1;
  47739. result.found = true;
  47740. return result;
  47741. }
  47742. if (r2 > 0 && r2 < maxR) {
  47743. result.root = r2;
  47744. result.found = true;
  47745. return result;
  47746. }
  47747. return result;
  47748. };
  47749. })();
  47750. var Collider = /** @class */ (function () {
  47751. function Collider() {
  47752. this._collisionPoint = BABYLON.Vector3.Zero();
  47753. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47754. this._tempVector = BABYLON.Vector3.Zero();
  47755. this._tempVector2 = BABYLON.Vector3.Zero();
  47756. this._tempVector3 = BABYLON.Vector3.Zero();
  47757. this._tempVector4 = BABYLON.Vector3.Zero();
  47758. this._edge = BABYLON.Vector3.Zero();
  47759. this._baseToVertex = BABYLON.Vector3.Zero();
  47760. this._destinationPoint = BABYLON.Vector3.Zero();
  47761. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47762. this._displacementVector = BABYLON.Vector3.Zero();
  47763. this._radius = BABYLON.Vector3.One();
  47764. this._retry = 0;
  47765. this._basePointWorld = BABYLON.Vector3.Zero();
  47766. this._velocityWorld = BABYLON.Vector3.Zero();
  47767. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47768. this._collisionMask = -1;
  47769. }
  47770. Object.defineProperty(Collider.prototype, "collisionMask", {
  47771. get: function () {
  47772. return this._collisionMask;
  47773. },
  47774. set: function (mask) {
  47775. this._collisionMask = !isNaN(mask) ? mask : -1;
  47776. },
  47777. enumerable: true,
  47778. configurable: true
  47779. });
  47780. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47781. /**
  47782. * Gets the plane normal used to compute the sliding response (in local space)
  47783. */
  47784. get: function () {
  47785. return this._slidePlaneNormal;
  47786. },
  47787. enumerable: true,
  47788. configurable: true
  47789. });
  47790. // Methods
  47791. Collider.prototype._initialize = function (source, dir, e) {
  47792. this._velocity = dir;
  47793. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47794. this._basePoint = source;
  47795. source.multiplyToRef(this._radius, this._basePointWorld);
  47796. dir.multiplyToRef(this._radius, this._velocityWorld);
  47797. this._velocityWorldLength = this._velocityWorld.length();
  47798. this._epsilon = e;
  47799. this.collisionFound = false;
  47800. };
  47801. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47802. pa.subtractToRef(point, this._tempVector);
  47803. pb.subtractToRef(point, this._tempVector2);
  47804. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47805. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47806. if (d < 0)
  47807. return false;
  47808. pc.subtractToRef(point, this._tempVector3);
  47809. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47810. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47811. if (d < 0)
  47812. return false;
  47813. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47814. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47815. return d >= 0;
  47816. };
  47817. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47818. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47819. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47820. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47821. return false;
  47822. }
  47823. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47824. return false;
  47825. return true;
  47826. };
  47827. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47828. var t0;
  47829. var embeddedInPlane = false;
  47830. //defensive programming, actually not needed.
  47831. if (!trianglePlaneArray) {
  47832. trianglePlaneArray = [];
  47833. }
  47834. if (!trianglePlaneArray[faceIndex]) {
  47835. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47836. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47837. }
  47838. var trianglePlane = trianglePlaneArray[faceIndex];
  47839. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47840. return;
  47841. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47842. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47843. if (normalDotVelocity == 0) {
  47844. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47845. return;
  47846. embeddedInPlane = true;
  47847. t0 = 0;
  47848. }
  47849. else {
  47850. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47851. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47852. if (t0 > t1) {
  47853. var temp = t1;
  47854. t1 = t0;
  47855. t0 = temp;
  47856. }
  47857. if (t0 > 1.0 || t1 < 0.0)
  47858. return;
  47859. if (t0 < 0)
  47860. t0 = 0;
  47861. if (t0 > 1.0)
  47862. t0 = 1.0;
  47863. }
  47864. this._collisionPoint.copyFromFloats(0, 0, 0);
  47865. var found = false;
  47866. var t = 1.0;
  47867. if (!embeddedInPlane) {
  47868. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47869. this._velocity.scaleToRef(t0, this._tempVector);
  47870. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47871. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47872. found = true;
  47873. t = t0;
  47874. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47875. }
  47876. }
  47877. if (!found) {
  47878. var velocitySquaredLength = this._velocity.lengthSquared();
  47879. var a = velocitySquaredLength;
  47880. this._basePoint.subtractToRef(p1, this._tempVector);
  47881. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47882. var c = this._tempVector.lengthSquared() - 1.0;
  47883. var lowestRoot = getLowestRoot(a, b, c, t);
  47884. if (lowestRoot.found) {
  47885. t = lowestRoot.root;
  47886. found = true;
  47887. this._collisionPoint.copyFrom(p1);
  47888. }
  47889. this._basePoint.subtractToRef(p2, this._tempVector);
  47890. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47891. c = this._tempVector.lengthSquared() - 1.0;
  47892. lowestRoot = getLowestRoot(a, b, c, t);
  47893. if (lowestRoot.found) {
  47894. t = lowestRoot.root;
  47895. found = true;
  47896. this._collisionPoint.copyFrom(p2);
  47897. }
  47898. this._basePoint.subtractToRef(p3, this._tempVector);
  47899. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47900. c = this._tempVector.lengthSquared() - 1.0;
  47901. lowestRoot = getLowestRoot(a, b, c, t);
  47902. if (lowestRoot.found) {
  47903. t = lowestRoot.root;
  47904. found = true;
  47905. this._collisionPoint.copyFrom(p3);
  47906. }
  47907. p2.subtractToRef(p1, this._edge);
  47908. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47909. var edgeSquaredLength = this._edge.lengthSquared();
  47910. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47911. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47912. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47913. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47914. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47915. lowestRoot = getLowestRoot(a, b, c, t);
  47916. if (lowestRoot.found) {
  47917. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47918. if (f >= 0.0 && f <= 1.0) {
  47919. t = lowestRoot.root;
  47920. found = true;
  47921. this._edge.scaleInPlace(f);
  47922. p1.addToRef(this._edge, this._collisionPoint);
  47923. }
  47924. }
  47925. p3.subtractToRef(p2, this._edge);
  47926. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47927. edgeSquaredLength = this._edge.lengthSquared();
  47928. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47929. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47930. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47931. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47932. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47933. lowestRoot = getLowestRoot(a, b, c, t);
  47934. if (lowestRoot.found) {
  47935. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47936. if (f >= 0.0 && f <= 1.0) {
  47937. t = lowestRoot.root;
  47938. found = true;
  47939. this._edge.scaleInPlace(f);
  47940. p2.addToRef(this._edge, this._collisionPoint);
  47941. }
  47942. }
  47943. p1.subtractToRef(p3, this._edge);
  47944. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47945. edgeSquaredLength = this._edge.lengthSquared();
  47946. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47947. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47948. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47949. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47950. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47951. lowestRoot = getLowestRoot(a, b, c, t);
  47952. if (lowestRoot.found) {
  47953. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47954. if (f >= 0.0 && f <= 1.0) {
  47955. t = lowestRoot.root;
  47956. found = true;
  47957. this._edge.scaleInPlace(f);
  47958. p3.addToRef(this._edge, this._collisionPoint);
  47959. }
  47960. }
  47961. }
  47962. if (found) {
  47963. var distToCollision = t * this._velocity.length();
  47964. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47965. if (!this.intersectionPoint) {
  47966. this.intersectionPoint = this._collisionPoint.clone();
  47967. }
  47968. else {
  47969. this.intersectionPoint.copyFrom(this._collisionPoint);
  47970. }
  47971. this._nearestDistance = distToCollision;
  47972. this.collisionFound = true;
  47973. }
  47974. }
  47975. };
  47976. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47977. for (var i = indexStart; i < indexEnd; i += 3) {
  47978. var p1 = pts[indices[i] - decal];
  47979. var p2 = pts[indices[i + 1] - decal];
  47980. var p3 = pts[indices[i + 2] - decal];
  47981. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47982. }
  47983. };
  47984. Collider.prototype._getResponse = function (pos, vel) {
  47985. pos.addToRef(vel, this._destinationPoint);
  47986. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47987. this._basePoint.addToRef(vel, pos);
  47988. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47989. this._slidePlaneNormal.normalize();
  47990. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47991. pos.addInPlace(this._displacementVector);
  47992. this.intersectionPoint.addInPlace(this._displacementVector);
  47993. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47994. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47995. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47996. };
  47997. return Collider;
  47998. }());
  47999. BABYLON.Collider = Collider;
  48000. })(BABYLON || (BABYLON = {}));
  48001. //# sourceMappingURL=babylon.collider.js.map
  48002. var BABYLON;
  48003. (function (BABYLON) {
  48004. //WebWorker code will be inserted to this variable.
  48005. BABYLON.CollisionWorker = "";
  48006. var WorkerTaskType;
  48007. (function (WorkerTaskType) {
  48008. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  48009. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  48010. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  48011. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  48012. var WorkerReplyType;
  48013. (function (WorkerReplyType) {
  48014. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  48015. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  48016. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  48017. var CollisionCoordinatorWorker = /** @class */ (function () {
  48018. function CollisionCoordinatorWorker() {
  48019. var _this = this;
  48020. this._scaledPosition = BABYLON.Vector3.Zero();
  48021. this._scaledVelocity = BABYLON.Vector3.Zero();
  48022. this.onMeshUpdated = function (transformNode) {
  48023. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  48024. };
  48025. this.onGeometryUpdated = function (geometry) {
  48026. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  48027. };
  48028. this._afterRender = function () {
  48029. if (!_this._init)
  48030. return;
  48031. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  48032. return;
  48033. }
  48034. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  48035. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  48036. if (_this._runningUpdated > 4) {
  48037. return;
  48038. }
  48039. ++_this._runningUpdated;
  48040. var payload = {
  48041. updatedMeshes: _this._addUpdateMeshesList,
  48042. updatedGeometries: _this._addUpdateGeometriesList,
  48043. removedGeometries: _this._toRemoveGeometryArray,
  48044. removedMeshes: _this._toRemoveMeshesArray
  48045. };
  48046. var message = {
  48047. payload: payload,
  48048. taskType: WorkerTaskType.UPDATE
  48049. };
  48050. var serializable = [];
  48051. for (var id in payload.updatedGeometries) {
  48052. if (payload.updatedGeometries.hasOwnProperty(id)) {
  48053. //prepare transferables
  48054. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  48055. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  48056. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  48057. }
  48058. }
  48059. _this._worker.postMessage(message, serializable);
  48060. _this._addUpdateMeshesList = {};
  48061. _this._addUpdateGeometriesList = {};
  48062. _this._toRemoveGeometryArray = [];
  48063. _this._toRemoveMeshesArray = [];
  48064. };
  48065. this._onMessageFromWorker = function (e) {
  48066. var returnData = e.data;
  48067. if (returnData.error != WorkerReplyType.SUCCESS) {
  48068. //TODO what errors can be returned from the worker?
  48069. BABYLON.Tools.Warn("error returned from worker!");
  48070. return;
  48071. }
  48072. switch (returnData.taskType) {
  48073. case WorkerTaskType.INIT:
  48074. _this._init = true;
  48075. //Update the worked with ALL of the scene's current state
  48076. _this._scene.meshes.forEach(function (mesh) {
  48077. _this.onMeshAdded(mesh);
  48078. });
  48079. _this._scene.getGeometries().forEach(function (geometry) {
  48080. _this.onGeometryAdded(geometry);
  48081. });
  48082. break;
  48083. case WorkerTaskType.UPDATE:
  48084. _this._runningUpdated--;
  48085. break;
  48086. case WorkerTaskType.COLLIDE:
  48087. var returnPayload = returnData.payload;
  48088. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  48089. return;
  48090. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  48091. if (callback) {
  48092. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  48093. if (mesh) {
  48094. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  48095. }
  48096. }
  48097. //cleanup
  48098. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  48099. break;
  48100. }
  48101. };
  48102. this._collisionsCallbackArray = [];
  48103. this._init = false;
  48104. this._runningUpdated = 0;
  48105. this._addUpdateMeshesList = {};
  48106. this._addUpdateGeometriesList = {};
  48107. this._toRemoveGeometryArray = [];
  48108. this._toRemoveMeshesArray = [];
  48109. }
  48110. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  48111. if (!this._init)
  48112. return;
  48113. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  48114. return;
  48115. position.divideToRef(collider._radius, this._scaledPosition);
  48116. displacement.divideToRef(collider._radius, this._scaledVelocity);
  48117. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  48118. var payload = {
  48119. collider: {
  48120. position: this._scaledPosition.asArray(),
  48121. velocity: this._scaledVelocity.asArray(),
  48122. radius: collider._radius.asArray()
  48123. },
  48124. collisionId: collisionIndex,
  48125. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  48126. maximumRetry: maximumRetry
  48127. };
  48128. var message = {
  48129. payload: payload,
  48130. taskType: WorkerTaskType.COLLIDE
  48131. };
  48132. this._worker.postMessage(message);
  48133. };
  48134. CollisionCoordinatorWorker.prototype.init = function (scene) {
  48135. this._scene = scene;
  48136. this._scene.registerAfterRender(this._afterRender);
  48137. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  48138. this._worker = new Worker(workerUrl);
  48139. this._worker.onmessage = this._onMessageFromWorker;
  48140. var message = {
  48141. payload: {},
  48142. taskType: WorkerTaskType.INIT
  48143. };
  48144. this._worker.postMessage(message);
  48145. };
  48146. CollisionCoordinatorWorker.prototype.destroy = function () {
  48147. this._scene.unregisterAfterRender(this._afterRender);
  48148. this._worker.terminate();
  48149. };
  48150. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  48151. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  48152. this.onMeshUpdated(mesh);
  48153. };
  48154. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  48155. this._toRemoveMeshesArray.push(mesh.uniqueId);
  48156. };
  48157. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  48158. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  48159. geometry.onGeometryUpdated = this.onGeometryUpdated;
  48160. this.onGeometryUpdated(geometry);
  48161. };
  48162. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  48163. this._toRemoveGeometryArray.push(geometry.id);
  48164. };
  48165. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  48166. var submeshes = [];
  48167. if (mesh.subMeshes) {
  48168. submeshes = mesh.subMeshes.map(function (sm, idx) {
  48169. var boundingInfo = sm.getBoundingInfo();
  48170. return {
  48171. position: idx,
  48172. verticesStart: sm.verticesStart,
  48173. verticesCount: sm.verticesCount,
  48174. indexStart: sm.indexStart,
  48175. indexCount: sm.indexCount,
  48176. hasMaterial: !!sm.getMaterial(),
  48177. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  48178. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  48179. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  48180. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  48181. };
  48182. });
  48183. }
  48184. var geometryId = null;
  48185. if (mesh instanceof BABYLON.Mesh) {
  48186. var geometry = mesh.geometry;
  48187. geometryId = geometry ? geometry.id : null;
  48188. }
  48189. else if (mesh instanceof BABYLON.InstancedMesh) {
  48190. var geometry = mesh.sourceMesh.geometry;
  48191. geometryId = geometry ? geometry.id : null;
  48192. }
  48193. var boundingInfo = mesh.getBoundingInfo();
  48194. return {
  48195. uniqueId: mesh.uniqueId,
  48196. id: mesh.id,
  48197. name: mesh.name,
  48198. geometryId: geometryId,
  48199. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  48200. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  48201. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  48202. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  48203. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  48204. subMeshes: submeshes,
  48205. checkCollisions: mesh.checkCollisions
  48206. };
  48207. };
  48208. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  48209. return {
  48210. id: geometry.id,
  48211. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  48212. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  48213. indices: new Uint32Array(geometry.getIndices() || []),
  48214. };
  48215. };
  48216. return CollisionCoordinatorWorker;
  48217. }());
  48218. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  48219. var CollisionCoordinatorLegacy = /** @class */ (function () {
  48220. function CollisionCoordinatorLegacy() {
  48221. this._scaledPosition = BABYLON.Vector3.Zero();
  48222. this._scaledVelocity = BABYLON.Vector3.Zero();
  48223. this._finalPosition = BABYLON.Vector3.Zero();
  48224. }
  48225. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  48226. position.divideToRef(collider._radius, this._scaledPosition);
  48227. displacement.divideToRef(collider._radius, this._scaledVelocity);
  48228. collider.collidedMesh = null;
  48229. collider._retry = 0;
  48230. collider._initialVelocity = this._scaledVelocity;
  48231. collider._initialPosition = this._scaledPosition;
  48232. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  48233. this._finalPosition.multiplyInPlace(collider._radius);
  48234. //run the callback
  48235. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  48236. };
  48237. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  48238. this._scene = scene;
  48239. };
  48240. CollisionCoordinatorLegacy.prototype.destroy = function () {
  48241. //Legacy need no destruction method.
  48242. };
  48243. //No update in legacy mode
  48244. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  48245. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  48246. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  48247. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  48248. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48249. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48250. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48251. if (excludedMesh === void 0) { excludedMesh = null; }
  48252. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48253. if (collider._retry >= maximumRetry) {
  48254. finalPosition.copyFrom(position);
  48255. return;
  48256. }
  48257. // Check if this is a mesh else camera or -1
  48258. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48259. collider._initialize(position, velocity, closeDistance);
  48260. // Check all meshes
  48261. for (var index = 0; index < this._scene.meshes.length; index++) {
  48262. var mesh = this._scene.meshes[index];
  48263. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48264. mesh._checkCollision(collider);
  48265. }
  48266. }
  48267. if (!collider.collisionFound) {
  48268. position.addToRef(velocity, finalPosition);
  48269. return;
  48270. }
  48271. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48272. collider._getResponse(position, velocity);
  48273. }
  48274. if (velocity.length() <= closeDistance) {
  48275. finalPosition.copyFrom(position);
  48276. return;
  48277. }
  48278. collider._retry++;
  48279. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48280. };
  48281. return CollisionCoordinatorLegacy;
  48282. }());
  48283. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48284. })(BABYLON || (BABYLON = {}));
  48285. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48286. var BABYLON;
  48287. (function (BABYLON) {
  48288. /**
  48289. * A particle represents one of the element emitted by a particle system.
  48290. * This is mainly define by its coordinates, direction, velocity and age.
  48291. */
  48292. var Particle = /** @class */ (function () {
  48293. /**
  48294. * Creates a new instance of @see Particle
  48295. * @param particleSystem the particle system the particle belongs to
  48296. */
  48297. function Particle(particleSystem) {
  48298. this.particleSystem = particleSystem;
  48299. /**
  48300. * The world position of the particle in the scene.
  48301. */
  48302. this.position = BABYLON.Vector3.Zero();
  48303. /**
  48304. * The world direction of the particle in the scene.
  48305. */
  48306. this.direction = BABYLON.Vector3.Zero();
  48307. /**
  48308. * The color of the particle.
  48309. */
  48310. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48311. /**
  48312. * The color change of the particle per step.
  48313. */
  48314. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48315. /**
  48316. * Defines how long will the life of the particle be.
  48317. */
  48318. this.lifeTime = 1.0;
  48319. /**
  48320. * The current age of the particle.
  48321. */
  48322. this.age = 0;
  48323. /**
  48324. * The current size of the particle.
  48325. */
  48326. this.size = 0;
  48327. /**
  48328. * The current angle of the particle.
  48329. */
  48330. this.angle = 0;
  48331. /**
  48332. * Defines how fast is the angle changing.
  48333. */
  48334. this.angularSpeed = 0;
  48335. /**
  48336. * Defines the cell index used by the particle to be rendered from a sprite.
  48337. */
  48338. this.cellIndex = 0;
  48339. this._currentFrameCounter = 0;
  48340. if (!this.particleSystem.isAnimationSheetEnabled) {
  48341. return;
  48342. }
  48343. this.cellIndex = this.particleSystem.startSpriteCellID;
  48344. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48345. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48346. }
  48347. else {
  48348. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48349. }
  48350. }
  48351. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48352. // (ageOffset / scaledUpdateSpeed) / available cells
  48353. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48354. this._currentFrameCounter += scaledUpdateSpeed;
  48355. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48356. this._currentFrameCounter = 0;
  48357. this.cellIndex++;
  48358. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48359. this.cellIndex = this.particleSystem.endSpriteCellID;
  48360. }
  48361. }
  48362. };
  48363. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48364. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48365. this.cellIndex++;
  48366. this._currentFrameCounter = 0;
  48367. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48368. if (this.particleSystem.spriteCellLoop) {
  48369. this.cellIndex = this.particleSystem.startSpriteCellID;
  48370. }
  48371. else {
  48372. this.cellIndex = this.particleSystem.endSpriteCellID;
  48373. }
  48374. }
  48375. }
  48376. else {
  48377. this._currentFrameCounter++;
  48378. }
  48379. };
  48380. /**
  48381. * Copy the properties of particle to another one.
  48382. * @param other the particle to copy the information to.
  48383. */
  48384. Particle.prototype.copyTo = function (other) {
  48385. other.position.copyFrom(this.position);
  48386. other.direction.copyFrom(this.direction);
  48387. other.color.copyFrom(this.color);
  48388. other.colorStep.copyFrom(this.colorStep);
  48389. other.lifeTime = this.lifeTime;
  48390. other.age = this.age;
  48391. other.size = this.size;
  48392. other.angle = this.angle;
  48393. other.angularSpeed = this.angularSpeed;
  48394. other.particleSystem = this.particleSystem;
  48395. other.cellIndex = this.cellIndex;
  48396. };
  48397. return Particle;
  48398. }());
  48399. BABYLON.Particle = Particle;
  48400. })(BABYLON || (BABYLON = {}));
  48401. //# sourceMappingURL=babylon.particle.js.map
  48402. var BABYLON;
  48403. (function (BABYLON) {
  48404. /**
  48405. * This represents a particle system in Babylon.
  48406. * 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.
  48407. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48408. * @example https://doc.babylonjs.com/babylon101/particles
  48409. */
  48410. var ParticleSystem = /** @class */ (function () {
  48411. /**
  48412. * Instantiates a particle system.
  48413. * 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.
  48414. * @param name The name of the particle system
  48415. * @param capacity The max number of particles alive at the same time
  48416. * @param scene The scene the particle system belongs to
  48417. * @param customEffect a custom effect used to change the way particles are rendered by default
  48418. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48419. * @param epsilon Offset used to render the particles
  48420. */
  48421. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48422. if (customEffect === void 0) { customEffect = null; }
  48423. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48424. if (epsilon === void 0) { epsilon = 0.01; }
  48425. var _this = this;
  48426. /**
  48427. * List of animations used by the particle system.
  48428. */
  48429. this.animations = [];
  48430. /**
  48431. * The rendering group used by the Particle system to chose when to render.
  48432. */
  48433. this.renderingGroupId = 0;
  48434. /**
  48435. * The emitter represents the Mesh or position we are attaching the particle system to.
  48436. */
  48437. this.emitter = null;
  48438. /**
  48439. * The density of particles, the rate of particle flow
  48440. */
  48441. this.emitRate = 10;
  48442. /**
  48443. * If you want to launch only a few particles at once, that can be done, as well.
  48444. */
  48445. this.manualEmitCount = -1;
  48446. /**
  48447. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48448. */
  48449. this.updateSpeed = 0.01;
  48450. /**
  48451. * The amount of time the particle system is running (depends of the overall speed above).
  48452. */
  48453. this.targetStopDuration = 0;
  48454. /**
  48455. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48456. */
  48457. this.disposeOnStop = false;
  48458. /**
  48459. * Minimum power of emitting particles.
  48460. */
  48461. this.minEmitPower = 1;
  48462. /**
  48463. * Maximum power of emitting particles.
  48464. */
  48465. this.maxEmitPower = 1;
  48466. /**
  48467. * Minimum life time of emitting particles.
  48468. */
  48469. this.minLifeTime = 1;
  48470. /**
  48471. * Maximum life time of emitting particles.
  48472. */
  48473. this.maxLifeTime = 1;
  48474. /**
  48475. * Minimum Size of emitting particles.
  48476. */
  48477. this.minSize = 1;
  48478. /**
  48479. * Maximum Size of emitting particles.
  48480. */
  48481. this.maxSize = 1;
  48482. /**
  48483. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48484. */
  48485. this.minAngularSpeed = 0;
  48486. /**
  48487. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48488. */
  48489. this.maxAngularSpeed = 0;
  48490. /**
  48491. * The layer mask we are rendering the particles through.
  48492. */
  48493. this.layerMask = 0x0FFFFFFF;
  48494. /**
  48495. * This can help using your own shader to render the particle system.
  48496. * The according effect will be created
  48497. */
  48498. this.customShader = null;
  48499. /**
  48500. * By default particle system starts as soon as they are created. This prevents the
  48501. * automatic start to happen and let you decide when to start emitting particles.
  48502. */
  48503. this.preventAutoStart = false;
  48504. /**
  48505. * Callback triggered when the particle animation is ending.
  48506. */
  48507. this.onAnimationEnd = null;
  48508. /**
  48509. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48510. */
  48511. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48512. /**
  48513. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48514. * to override the particles.
  48515. */
  48516. this.forceDepthWrite = false;
  48517. /**
  48518. * You can use gravity if you want to give an orientation to your particles.
  48519. */
  48520. this.gravity = BABYLON.Vector3.Zero();
  48521. /**
  48522. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48523. */
  48524. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48525. /**
  48526. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48527. */
  48528. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48529. /**
  48530. * 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.
  48531. */
  48532. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48533. /**
  48534. * 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.
  48535. */
  48536. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48537. /**
  48538. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48539. */
  48540. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48541. /**
  48542. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48543. */
  48544. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48545. /**
  48546. * Color the particle will have at the end of its lifetime.
  48547. */
  48548. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48549. /**
  48550. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48551. */
  48552. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48553. /**
  48554. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48555. */
  48556. this.spriteCellLoop = true;
  48557. /**
  48558. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48559. */
  48560. this.spriteCellChangeSpeed = 0;
  48561. /**
  48562. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48563. */
  48564. this.startSpriteCellID = 0;
  48565. /**
  48566. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48567. */
  48568. this.endSpriteCellID = 0;
  48569. /**
  48570. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48571. */
  48572. this.spriteCellWidth = 0;
  48573. /**
  48574. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48575. */
  48576. this.spriteCellHeight = 0;
  48577. /**
  48578. * An event triggered when the system is disposed.
  48579. */
  48580. this.onDisposeObservable = new BABYLON.Observable();
  48581. this._particles = new Array();
  48582. this._stockParticles = new Array();
  48583. this._newPartsExcess = 0;
  48584. this._vertexBuffers = {};
  48585. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48586. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48587. this._scaledDirection = BABYLON.Vector3.Zero();
  48588. this._scaledGravity = BABYLON.Vector3.Zero();
  48589. this._currentRenderId = -1;
  48590. this._started = false;
  48591. this._stopped = false;
  48592. this._actualFrame = 0;
  48593. this._vertexBufferSize = 11;
  48594. this._appendParticleVertexes = null;
  48595. this.id = name;
  48596. this.name = name;
  48597. this._capacity = capacity;
  48598. this._epsilon = epsilon;
  48599. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48600. if (isAnimationSheetEnabled) {
  48601. this._vertexBufferSize = 12;
  48602. }
  48603. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48604. this._customEffect = customEffect;
  48605. scene.particleSystems.push(this);
  48606. this._createIndexBuffer();
  48607. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48608. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48609. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48610. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48611. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48612. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48613. if (this._isAnimationSheetEnabled) {
  48614. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48615. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48616. }
  48617. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48618. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48619. this._vertexBuffers["options"] = options;
  48620. // Default behaviors
  48621. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48622. this.updateFunction = function (particles) {
  48623. for (var index = 0; index < particles.length; index++) {
  48624. var particle = particles[index];
  48625. particle.age += _this._scaledUpdateSpeed;
  48626. if (particle.age >= particle.lifeTime) {
  48627. _this.recycleParticle(particle);
  48628. index--;
  48629. continue;
  48630. }
  48631. else {
  48632. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48633. particle.color.addInPlace(_this._scaledColorStep);
  48634. if (particle.color.a < 0)
  48635. particle.color.a = 0;
  48636. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48637. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48638. particle.position.addInPlace(_this._scaledDirection);
  48639. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48640. particle.direction.addInPlace(_this._scaledGravity);
  48641. if (_this._isAnimationSheetEnabled) {
  48642. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48643. }
  48644. }
  48645. }
  48646. };
  48647. }
  48648. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48649. /**
  48650. * Sets a callback that will be triggered when the system is disposed.
  48651. */
  48652. set: function (callback) {
  48653. if (this._onDisposeObserver) {
  48654. this.onDisposeObservable.remove(this._onDisposeObserver);
  48655. }
  48656. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48657. },
  48658. enumerable: true,
  48659. configurable: true
  48660. });
  48661. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48662. /**
  48663. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48664. */
  48665. get: function () {
  48666. return this._isAnimationSheetEnabled;
  48667. },
  48668. enumerable: true,
  48669. configurable: true
  48670. });
  48671. ParticleSystem.prototype._createIndexBuffer = function () {
  48672. var indices = [];
  48673. var index = 0;
  48674. for (var count = 0; count < this._capacity; count++) {
  48675. indices.push(index);
  48676. indices.push(index + 1);
  48677. indices.push(index + 2);
  48678. indices.push(index);
  48679. indices.push(index + 2);
  48680. indices.push(index + 3);
  48681. index += 4;
  48682. }
  48683. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48684. };
  48685. /**
  48686. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48687. * Its lifetime will start back at 0.
  48688. * @param particle The particle to recycle
  48689. */
  48690. ParticleSystem.prototype.recycleParticle = function (particle) {
  48691. var lastParticle = this._particles.pop();
  48692. if (lastParticle !== particle) {
  48693. lastParticle.copyTo(particle);
  48694. this._stockParticles.push(lastParticle);
  48695. }
  48696. };
  48697. /**
  48698. * Gets the maximum number of particles active at the same time.
  48699. * @returns The max number of active particles.
  48700. */
  48701. ParticleSystem.prototype.getCapacity = function () {
  48702. return this._capacity;
  48703. };
  48704. /**
  48705. * Gets Wether there are still active particles in the system.
  48706. * @returns True if it is alive, otherwise false.
  48707. */
  48708. ParticleSystem.prototype.isAlive = function () {
  48709. return this._alive;
  48710. };
  48711. /**
  48712. * Gets Wether the system has been started.
  48713. * @returns True if it has been started, otherwise false.
  48714. */
  48715. ParticleSystem.prototype.isStarted = function () {
  48716. return this._started;
  48717. };
  48718. /**
  48719. * Starts the particle system and begins to emit.
  48720. */
  48721. ParticleSystem.prototype.start = function () {
  48722. this._started = true;
  48723. this._stopped = false;
  48724. this._actualFrame = 0;
  48725. };
  48726. /**
  48727. * Stops the particle system.
  48728. */
  48729. ParticleSystem.prototype.stop = function () {
  48730. this._stopped = true;
  48731. };
  48732. /**
  48733. * @ignore (for internal use only)
  48734. */
  48735. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48736. var offset = index * this._vertexBufferSize;
  48737. this._vertexData[offset] = particle.position.x;
  48738. this._vertexData[offset + 1] = particle.position.y;
  48739. this._vertexData[offset + 2] = particle.position.z;
  48740. this._vertexData[offset + 3] = particle.color.r;
  48741. this._vertexData[offset + 4] = particle.color.g;
  48742. this._vertexData[offset + 5] = particle.color.b;
  48743. this._vertexData[offset + 6] = particle.color.a;
  48744. this._vertexData[offset + 7] = particle.angle;
  48745. this._vertexData[offset + 8] = particle.size;
  48746. this._vertexData[offset + 9] = offsetX;
  48747. this._vertexData[offset + 10] = offsetY;
  48748. };
  48749. /**
  48750. * @ignore (for internal use only)
  48751. */
  48752. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48753. if (offsetX === 0)
  48754. offsetX = this._epsilon;
  48755. else if (offsetX === 1)
  48756. offsetX = 1 - this._epsilon;
  48757. if (offsetY === 0)
  48758. offsetY = this._epsilon;
  48759. else if (offsetY === 1)
  48760. offsetY = 1 - this._epsilon;
  48761. var offset = index * this._vertexBufferSize;
  48762. this._vertexData[offset] = particle.position.x;
  48763. this._vertexData[offset + 1] = particle.position.y;
  48764. this._vertexData[offset + 2] = particle.position.z;
  48765. this._vertexData[offset + 3] = particle.color.r;
  48766. this._vertexData[offset + 4] = particle.color.g;
  48767. this._vertexData[offset + 5] = particle.color.b;
  48768. this._vertexData[offset + 6] = particle.color.a;
  48769. this._vertexData[offset + 7] = particle.angle;
  48770. this._vertexData[offset + 8] = particle.size;
  48771. this._vertexData[offset + 9] = offsetX;
  48772. this._vertexData[offset + 10] = offsetY;
  48773. this._vertexData[offset + 11] = particle.cellIndex;
  48774. };
  48775. ParticleSystem.prototype._update = function (newParticles) {
  48776. // Update current
  48777. this._alive = this._particles.length > 0;
  48778. this.updateFunction(this._particles);
  48779. // Add new ones
  48780. var worldMatrix;
  48781. if (this.emitter.position) {
  48782. var emitterMesh = this.emitter;
  48783. worldMatrix = emitterMesh.getWorldMatrix();
  48784. }
  48785. else {
  48786. var emitterPosition = this.emitter;
  48787. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48788. }
  48789. var particle;
  48790. for (var index = 0; index < newParticles; index++) {
  48791. if (this._particles.length === this._capacity) {
  48792. break;
  48793. }
  48794. if (this._stockParticles.length !== 0) {
  48795. particle = this._stockParticles.pop();
  48796. particle.age = 0;
  48797. particle.cellIndex = this.startSpriteCellID;
  48798. }
  48799. else {
  48800. particle = new BABYLON.Particle(this);
  48801. }
  48802. this._particles.push(particle);
  48803. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48804. if (this.startPositionFunction) {
  48805. this.startPositionFunction(worldMatrix, particle.position, particle);
  48806. }
  48807. else {
  48808. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48809. }
  48810. if (this.startDirectionFunction) {
  48811. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48812. }
  48813. else {
  48814. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48815. }
  48816. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48817. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48818. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48819. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48820. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48821. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48822. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48823. }
  48824. };
  48825. ParticleSystem.prototype._getEffect = function () {
  48826. if (this._customEffect) {
  48827. return this._customEffect;
  48828. }
  48829. ;
  48830. var defines = [];
  48831. if (this._scene.clipPlane) {
  48832. defines.push("#define CLIPPLANE");
  48833. }
  48834. if (this._isAnimationSheetEnabled) {
  48835. defines.push("#define ANIMATESHEET");
  48836. }
  48837. // Effect
  48838. var join = defines.join("\n");
  48839. if (this._cachedDefines !== join) {
  48840. this._cachedDefines = join;
  48841. var attributesNamesOrOptions;
  48842. var effectCreationOption;
  48843. if (this._isAnimationSheetEnabled) {
  48844. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48845. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48846. }
  48847. else {
  48848. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48849. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48850. }
  48851. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48852. }
  48853. return this._effect;
  48854. };
  48855. /**
  48856. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48857. */
  48858. ParticleSystem.prototype.animate = function () {
  48859. if (!this._started)
  48860. return;
  48861. var effect = this._getEffect();
  48862. // Check
  48863. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48864. return;
  48865. if (this._currentRenderId === this._scene.getRenderId()) {
  48866. return;
  48867. }
  48868. this._currentRenderId = this._scene.getRenderId();
  48869. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48870. // determine the number of particles we need to create
  48871. var newParticles;
  48872. if (this.manualEmitCount > -1) {
  48873. newParticles = this.manualEmitCount;
  48874. this._newPartsExcess = 0;
  48875. this.manualEmitCount = 0;
  48876. }
  48877. else {
  48878. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48879. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48880. }
  48881. if (this._newPartsExcess > 1.0) {
  48882. newParticles += this._newPartsExcess >> 0;
  48883. this._newPartsExcess -= this._newPartsExcess >> 0;
  48884. }
  48885. this._alive = false;
  48886. if (!this._stopped) {
  48887. this._actualFrame += this._scaledUpdateSpeed;
  48888. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48889. this.stop();
  48890. }
  48891. else {
  48892. newParticles = 0;
  48893. }
  48894. this._update(newParticles);
  48895. // Stopped?
  48896. if (this._stopped) {
  48897. if (!this._alive) {
  48898. this._started = false;
  48899. if (this.onAnimationEnd) {
  48900. this.onAnimationEnd();
  48901. }
  48902. if (this.disposeOnStop) {
  48903. this._scene._toBeDisposed.push(this);
  48904. }
  48905. }
  48906. }
  48907. // Animation sheet
  48908. if (this._isAnimationSheetEnabled) {
  48909. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48910. }
  48911. else {
  48912. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48913. }
  48914. // Update VBO
  48915. var offset = 0;
  48916. for (var index = 0; index < this._particles.length; index++) {
  48917. var particle = this._particles[index];
  48918. this._appendParticleVertexes(offset, particle);
  48919. offset += 4;
  48920. }
  48921. if (this._vertexBuffer) {
  48922. this._vertexBuffer.update(this._vertexData);
  48923. }
  48924. };
  48925. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48926. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48927. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48928. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48929. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48930. };
  48931. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48932. this._appendParticleVertex(offset++, particle, 0, 0);
  48933. this._appendParticleVertex(offset++, particle, 1, 0);
  48934. this._appendParticleVertex(offset++, particle, 1, 1);
  48935. this._appendParticleVertex(offset++, particle, 0, 1);
  48936. };
  48937. /**
  48938. * Rebuilds the particle system.
  48939. */
  48940. ParticleSystem.prototype.rebuild = function () {
  48941. this._createIndexBuffer();
  48942. if (this._vertexBuffer) {
  48943. this._vertexBuffer._rebuild();
  48944. }
  48945. };
  48946. /**
  48947. * Renders the particle system in its current state.
  48948. * @returns the current number of particles.
  48949. */
  48950. ParticleSystem.prototype.render = function () {
  48951. var effect = this._getEffect();
  48952. // Check
  48953. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48954. return 0;
  48955. var engine = this._scene.getEngine();
  48956. // Render
  48957. engine.enableEffect(effect);
  48958. engine.setState(false);
  48959. var viewMatrix = this._scene.getViewMatrix();
  48960. effect.setTexture("diffuseSampler", this.particleTexture);
  48961. effect.setMatrix("view", viewMatrix);
  48962. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48963. if (this._isAnimationSheetEnabled) {
  48964. var baseSize = this.particleTexture.getBaseSize();
  48965. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48966. }
  48967. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48968. if (this._scene.clipPlane) {
  48969. var clipPlane = this._scene.clipPlane;
  48970. var invView = viewMatrix.clone();
  48971. invView.invert();
  48972. effect.setMatrix("invView", invView);
  48973. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48974. }
  48975. // VBOs
  48976. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48977. // Draw order
  48978. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48979. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48980. }
  48981. else {
  48982. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48983. }
  48984. if (this.forceDepthWrite) {
  48985. engine.setDepthWrite(true);
  48986. }
  48987. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48988. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48989. return this._particles.length;
  48990. };
  48991. /**
  48992. * Disposes the particle system and free the associated resources.
  48993. */
  48994. ParticleSystem.prototype.dispose = function () {
  48995. if (this._vertexBuffer) {
  48996. this._vertexBuffer.dispose();
  48997. this._vertexBuffer = null;
  48998. }
  48999. if (this._indexBuffer) {
  49000. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49001. this._indexBuffer = null;
  49002. }
  49003. if (this.particleTexture) {
  49004. this.particleTexture.dispose();
  49005. this.particleTexture = null;
  49006. }
  49007. // Remove from scene
  49008. var index = this._scene.particleSystems.indexOf(this);
  49009. if (index > -1) {
  49010. this._scene.particleSystems.splice(index, 1);
  49011. }
  49012. // Callback
  49013. this.onDisposeObservable.notifyObservers(this);
  49014. this.onDisposeObservable.clear();
  49015. };
  49016. /**
  49017. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  49018. * @param radius The radius of the sphere to emit from
  49019. * @returns the emitter
  49020. */
  49021. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  49022. if (radius === void 0) { radius = 1; }
  49023. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  49024. this.particleEmitterType = particleEmitter;
  49025. return particleEmitter;
  49026. };
  49027. /**
  49028. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  49029. * @param radius The radius of the sphere to emit from
  49030. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  49031. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  49032. * @returns the emitter
  49033. */
  49034. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  49035. if (radius === void 0) { radius = 1; }
  49036. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  49037. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  49038. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  49039. this.particleEmitterType = particleEmitter;
  49040. return particleEmitter;
  49041. };
  49042. /**
  49043. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  49044. * @param radius The radius of the cone to emit from
  49045. * @param angle The base angle of the cone
  49046. * @returns the emitter
  49047. */
  49048. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  49049. if (radius === void 0) { radius = 1; }
  49050. if (angle === void 0) { angle = Math.PI / 4; }
  49051. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  49052. this.particleEmitterType = particleEmitter;
  49053. return particleEmitter;
  49054. };
  49055. // 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.
  49056. /**
  49057. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  49058. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  49059. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  49060. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  49061. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  49062. * @returns the emitter
  49063. */
  49064. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  49065. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  49066. this.direction1 = direction1;
  49067. this.direction2 = direction2;
  49068. this.minEmitBox = minEmitBox;
  49069. this.maxEmitBox = maxEmitBox;
  49070. this.particleEmitterType = particleEmitter;
  49071. return particleEmitter;
  49072. };
  49073. /**
  49074. * Clones the particle system.
  49075. * @param name The name of the cloned object
  49076. * @param newEmitter The new emitter to use
  49077. * @returns the cloned particle system
  49078. */
  49079. ParticleSystem.prototype.clone = function (name, newEmitter) {
  49080. var custom = null;
  49081. var program = null;
  49082. if (this.customShader != null) {
  49083. program = this.customShader;
  49084. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  49085. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  49086. }
  49087. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  49088. result.customShader = program;
  49089. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  49090. if (newEmitter === undefined) {
  49091. newEmitter = this.emitter;
  49092. }
  49093. result.emitter = newEmitter;
  49094. if (this.particleTexture) {
  49095. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  49096. }
  49097. if (!this.preventAutoStart) {
  49098. result.start();
  49099. }
  49100. return result;
  49101. };
  49102. /**
  49103. * Serializes the particle system to a JSON object.
  49104. * @returns the JSON object
  49105. */
  49106. ParticleSystem.prototype.serialize = function () {
  49107. var serializationObject = {};
  49108. serializationObject.name = this.name;
  49109. serializationObject.id = this.id;
  49110. // Emitter
  49111. if (this.emitter.position) {
  49112. var emitterMesh = this.emitter;
  49113. serializationObject.emitterId = emitterMesh.id;
  49114. }
  49115. else {
  49116. var emitterPosition = this.emitter;
  49117. serializationObject.emitter = emitterPosition.asArray();
  49118. }
  49119. serializationObject.capacity = this.getCapacity();
  49120. if (this.particleTexture) {
  49121. serializationObject.textureName = this.particleTexture.name;
  49122. }
  49123. // Animations
  49124. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  49125. // Particle system
  49126. serializationObject.minAngularSpeed = this.minAngularSpeed;
  49127. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  49128. serializationObject.minSize = this.minSize;
  49129. serializationObject.maxSize = this.maxSize;
  49130. serializationObject.minEmitPower = this.minEmitPower;
  49131. serializationObject.maxEmitPower = this.maxEmitPower;
  49132. serializationObject.minLifeTime = this.minLifeTime;
  49133. serializationObject.maxLifeTime = this.maxLifeTime;
  49134. serializationObject.emitRate = this.emitRate;
  49135. serializationObject.minEmitBox = this.minEmitBox.asArray();
  49136. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  49137. serializationObject.gravity = this.gravity.asArray();
  49138. serializationObject.direction1 = this.direction1.asArray();
  49139. serializationObject.direction2 = this.direction2.asArray();
  49140. serializationObject.color1 = this.color1.asArray();
  49141. serializationObject.color2 = this.color2.asArray();
  49142. serializationObject.colorDead = this.colorDead.asArray();
  49143. serializationObject.updateSpeed = this.updateSpeed;
  49144. serializationObject.targetStopDuration = this.targetStopDuration;
  49145. serializationObject.textureMask = this.textureMask.asArray();
  49146. serializationObject.blendMode = this.blendMode;
  49147. serializationObject.customShader = this.customShader;
  49148. serializationObject.preventAutoStart = this.preventAutoStart;
  49149. serializationObject.startSpriteCellID = this.startSpriteCellID;
  49150. serializationObject.endSpriteCellID = this.endSpriteCellID;
  49151. serializationObject.spriteCellLoop = this.spriteCellLoop;
  49152. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  49153. serializationObject.spriteCellWidth = this.spriteCellWidth;
  49154. serializationObject.spriteCellHeight = this.spriteCellHeight;
  49155. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  49156. return serializationObject;
  49157. };
  49158. /**
  49159. * Parses a JSON object to create a particle system.
  49160. * @param parsedParticleSystem The JSON object to parse
  49161. * @param scene The scene to create the particle system in
  49162. * @param rootUrl The root url to use to load external dependencies like texture
  49163. * @returns the Parsed particle system
  49164. */
  49165. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  49166. var name = parsedParticleSystem.name;
  49167. var custom = null;
  49168. var program = null;
  49169. if (parsedParticleSystem.customShader) {
  49170. program = parsedParticleSystem.customShader;
  49171. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  49172. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  49173. }
  49174. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  49175. particleSystem.customShader = program;
  49176. if (parsedParticleSystem.id) {
  49177. particleSystem.id = parsedParticleSystem.id;
  49178. }
  49179. // Auto start
  49180. if (parsedParticleSystem.preventAutoStart) {
  49181. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  49182. }
  49183. // Texture
  49184. if (parsedParticleSystem.textureName) {
  49185. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  49186. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  49187. }
  49188. // Emitter
  49189. if (parsedParticleSystem.emitterId) {
  49190. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  49191. }
  49192. else {
  49193. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  49194. }
  49195. // Animations
  49196. if (parsedParticleSystem.animations) {
  49197. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  49198. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  49199. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49200. }
  49201. }
  49202. if (parsedParticleSystem.autoAnimate) {
  49203. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  49204. }
  49205. // Particle system
  49206. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  49207. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  49208. particleSystem.minSize = parsedParticleSystem.minSize;
  49209. particleSystem.maxSize = parsedParticleSystem.maxSize;
  49210. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  49211. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  49212. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  49213. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  49214. particleSystem.emitRate = parsedParticleSystem.emitRate;
  49215. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  49216. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  49217. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  49218. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  49219. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  49220. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  49221. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  49222. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  49223. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  49224. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  49225. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  49226. particleSystem.blendMode = parsedParticleSystem.blendMode;
  49227. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  49228. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  49229. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  49230. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  49231. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  49232. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  49233. if (!particleSystem.preventAutoStart) {
  49234. particleSystem.start();
  49235. }
  49236. return particleSystem;
  49237. };
  49238. /**
  49239. * Source color is added to the destination color without alpha affecting the result.
  49240. */
  49241. ParticleSystem.BLENDMODE_ONEONE = 0;
  49242. /**
  49243. * Blend current color and particle color using particle’s alpha.
  49244. */
  49245. ParticleSystem.BLENDMODE_STANDARD = 1;
  49246. return ParticleSystem;
  49247. }());
  49248. BABYLON.ParticleSystem = ParticleSystem;
  49249. })(BABYLON || (BABYLON = {}));
  49250. //# sourceMappingURL=babylon.particleSystem.js.map
  49251. var BABYLON;
  49252. (function (BABYLON) {
  49253. /**
  49254. * Particle emitter emitting particles from the inside of a box.
  49255. * It emits the particles randomly between 2 given directions.
  49256. */
  49257. var BoxParticleEmitter = /** @class */ (function () {
  49258. // to be updated like the rest of emitters when breaking changes.
  49259. // all property should be come public variables and passed through constructor.
  49260. /**
  49261. * Creates a new instance of @see BoxParticleEmitter
  49262. * @param _particleSystem the particle system associated with the emitter
  49263. */
  49264. function BoxParticleEmitter(_particleSystem) {
  49265. this._particleSystem = _particleSystem;
  49266. }
  49267. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49268. /**
  49269. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49270. */
  49271. get: function () {
  49272. return this._particleSystem.direction1;
  49273. },
  49274. /**
  49275. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49276. */
  49277. set: function (value) {
  49278. this._particleSystem.direction1 = value;
  49279. },
  49280. enumerable: true,
  49281. configurable: true
  49282. });
  49283. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49284. /**
  49285. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49286. */
  49287. get: function () {
  49288. return this._particleSystem.direction2;
  49289. },
  49290. /**
  49291. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49292. */
  49293. set: function (value) {
  49294. this._particleSystem.direction2 = value;
  49295. },
  49296. enumerable: true,
  49297. configurable: true
  49298. });
  49299. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49300. /**
  49301. * 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.
  49302. */
  49303. get: function () {
  49304. return this._particleSystem.minEmitBox;
  49305. },
  49306. /**
  49307. * 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.
  49308. */
  49309. set: function (value) {
  49310. this._particleSystem.minEmitBox = value;
  49311. },
  49312. enumerable: true,
  49313. configurable: true
  49314. });
  49315. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49316. /**
  49317. * 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.
  49318. */
  49319. get: function () {
  49320. return this._particleSystem.maxEmitBox;
  49321. },
  49322. /**
  49323. * 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.
  49324. */
  49325. set: function (value) {
  49326. this._particleSystem.maxEmitBox = value;
  49327. },
  49328. enumerable: true,
  49329. configurable: true
  49330. });
  49331. /**
  49332. * Called by the particle System when the direction is computed for the created particle.
  49333. * @param emitPower is the power of the particle (speed)
  49334. * @param worldMatrix is the world matrix of the particle system
  49335. * @param directionToUpdate is the direction vector to update with the result
  49336. * @param particle is the particle we are computed the direction for
  49337. */
  49338. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49339. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49340. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49341. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49342. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49343. };
  49344. /**
  49345. * Called by the particle System when the position is computed for the created particle.
  49346. * @param worldMatrix is the world matrix of the particle system
  49347. * @param positionToUpdate is the position vector to update with the result
  49348. * @param particle is the particle we are computed the position for
  49349. */
  49350. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49351. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49352. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49353. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49355. };
  49356. /**
  49357. * Clones the current emitter and returns a copy of it
  49358. * @returns the new emitter
  49359. */
  49360. BoxParticleEmitter.prototype.clone = function () {
  49361. var newOne = new BoxParticleEmitter(this._particleSystem);
  49362. BABYLON.Tools.DeepCopy(this, newOne);
  49363. return newOne;
  49364. };
  49365. return BoxParticleEmitter;
  49366. }());
  49367. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49368. })(BABYLON || (BABYLON = {}));
  49369. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49370. var BABYLON;
  49371. (function (BABYLON) {
  49372. /**
  49373. * Particle emitter emitting particles from the inside of a cone.
  49374. * It emits the particles alongside the cone volume from the base to the particle.
  49375. * The emission direction might be randomized.
  49376. */
  49377. var ConeParticleEmitter = /** @class */ (function () {
  49378. /**
  49379. * Creates a new instance of @see ConeParticleEmitter
  49380. * @param radius the radius of the emission cone
  49381. * @param angles the cone base angle
  49382. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49383. */
  49384. function ConeParticleEmitter(radius,
  49385. /**
  49386. * The radius of the emission cone.
  49387. */
  49388. angle,
  49389. /**
  49390. * The cone base angle.
  49391. */
  49392. directionRandomizer) {
  49393. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49394. this.angle = angle;
  49395. this.directionRandomizer = directionRandomizer;
  49396. this.radius = radius;
  49397. }
  49398. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49399. /**
  49400. * Gets the radius of the emission cone.
  49401. */
  49402. get: function () {
  49403. return this._radius;
  49404. },
  49405. /**
  49406. * Sets the radius of the emission cone.
  49407. */
  49408. set: function (value) {
  49409. this._radius = value;
  49410. if (this.angle !== 0) {
  49411. this._height = value / Math.tan(this.angle / 2);
  49412. }
  49413. else {
  49414. this._height = 1;
  49415. }
  49416. },
  49417. enumerable: true,
  49418. configurable: true
  49419. });
  49420. /**
  49421. * Called by the particle System when the direction is computed for the created particle.
  49422. * @param emitPower is the power of the particle (speed)
  49423. * @param worldMatrix is the world matrix of the particle system
  49424. * @param directionToUpdate is the direction vector to update with the result
  49425. * @param particle is the particle we are computed the direction for
  49426. */
  49427. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49428. if (this.angle === 0) {
  49429. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49430. }
  49431. else {
  49432. // measure the direction Vector from the emitter to the particle.
  49433. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49434. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49435. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49436. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49437. direction.x += randX;
  49438. direction.y += randY;
  49439. direction.z += randZ;
  49440. direction.normalize();
  49441. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49442. }
  49443. };
  49444. /**
  49445. * Called by the particle System when the position is computed for the created particle.
  49446. * @param worldMatrix is the world matrix of the particle system
  49447. * @param positionToUpdate is the position vector to update with the result
  49448. * @param particle is the particle we are computed the position for
  49449. */
  49450. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49451. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49452. var h = BABYLON.Scalar.RandomRange(0, 1);
  49453. // Better distribution in a cone at normal angles.
  49454. h = 1 - h * h;
  49455. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49456. radius = radius * h / this._height;
  49457. var randX = radius * Math.sin(s);
  49458. var randZ = radius * Math.cos(s);
  49459. var randY = h;
  49460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49461. };
  49462. /**
  49463. * Clones the current emitter and returns a copy of it
  49464. * @returns the new emitter
  49465. */
  49466. ConeParticleEmitter.prototype.clone = function () {
  49467. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49468. BABYLON.Tools.DeepCopy(this, newOne);
  49469. return newOne;
  49470. };
  49471. return ConeParticleEmitter;
  49472. }());
  49473. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49474. })(BABYLON || (BABYLON = {}));
  49475. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49476. var BABYLON;
  49477. (function (BABYLON) {
  49478. /**
  49479. * Particle emitter emitting particles from the inside of a sphere.
  49480. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49481. */
  49482. var SphereParticleEmitter = /** @class */ (function () {
  49483. /**
  49484. * Creates a new instance of @see SphereParticleEmitter
  49485. * @param radius the radius of the emission sphere
  49486. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49487. */
  49488. function SphereParticleEmitter(
  49489. /**
  49490. * The radius of the emission sphere.
  49491. */
  49492. radius,
  49493. /**
  49494. * How much to randomize the particle direction [0-1].
  49495. */
  49496. directionRandomizer) {
  49497. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49498. this.radius = radius;
  49499. this.directionRandomizer = directionRandomizer;
  49500. }
  49501. /**
  49502. * Called by the particle System when the direction is computed for the created particle.
  49503. * @param emitPower is the power of the particle (speed)
  49504. * @param worldMatrix is the world matrix of the particle system
  49505. * @param directionToUpdate is the direction vector to update with the result
  49506. * @param particle is the particle we are computed the direction for
  49507. */
  49508. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49509. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49510. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49511. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49512. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49513. direction.x += randX;
  49514. direction.y += randY;
  49515. direction.z += randZ;
  49516. direction.normalize();
  49517. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49518. };
  49519. /**
  49520. * Called by the particle System when the position is computed for the created particle.
  49521. * @param worldMatrix is the world matrix of the particle system
  49522. * @param positionToUpdate is the position vector to update with the result
  49523. * @param particle is the particle we are computed the position for
  49524. */
  49525. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49526. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49527. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49528. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49529. var randY = this.radius * Math.cos(theta);
  49530. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49531. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49532. };
  49533. /**
  49534. * Clones the current emitter and returns a copy of it
  49535. * @returns the new emitter
  49536. */
  49537. SphereParticleEmitter.prototype.clone = function () {
  49538. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49539. BABYLON.Tools.DeepCopy(this, newOne);
  49540. return newOne;
  49541. };
  49542. return SphereParticleEmitter;
  49543. }());
  49544. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49545. /**
  49546. * Particle emitter emitting particles from the inside of a sphere.
  49547. * It emits the particles randomly between two vectors.
  49548. */
  49549. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49550. __extends(SphereDirectedParticleEmitter, _super);
  49551. /**
  49552. * Creates a new instance of @see SphereDirectedParticleEmitter
  49553. * @param radius the radius of the emission sphere
  49554. * @param direction1 the min limit of the emission direction
  49555. * @param direction2 the max limit of the emission direction
  49556. */
  49557. function SphereDirectedParticleEmitter(radius,
  49558. /**
  49559. * The min limit of the emission direction.
  49560. */
  49561. direction1,
  49562. /**
  49563. * The max limit of the emission direction.
  49564. */
  49565. direction2) {
  49566. var _this = _super.call(this, radius) || this;
  49567. _this.direction1 = direction1;
  49568. _this.direction2 = direction2;
  49569. return _this;
  49570. }
  49571. /**
  49572. * Called by the particle System when the direction is computed for the created particle.
  49573. * @param emitPower is the power of the particle (speed)
  49574. * @param worldMatrix is the world matrix of the particle system
  49575. * @param directionToUpdate is the direction vector to update with the result
  49576. * @param particle is the particle we are computed the direction for
  49577. */
  49578. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49579. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49580. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49581. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49582. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49583. };
  49584. /**
  49585. * Clones the current emitter and returns a copy of it
  49586. * @returns the new emitter
  49587. */
  49588. SphereDirectedParticleEmitter.prototype.clone = function () {
  49589. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49590. BABYLON.Tools.DeepCopy(this, newOne);
  49591. return newOne;
  49592. };
  49593. return SphereDirectedParticleEmitter;
  49594. }(SphereParticleEmitter));
  49595. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49596. })(BABYLON || (BABYLON = {}));
  49597. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49598. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  49599. var BABYLON;
  49600. (function (BABYLON) {
  49601. /**
  49602. * Represents one particle of a solid particle system.
  49603. * @see SolidParticleSystem
  49604. */
  49605. var SolidParticle = /** @class */ (function () {
  49606. /**
  49607. * Creates a Solid Particle object.
  49608. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49609. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49610. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49611. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49612. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49613. * @param shapeId (integer) is the model shape identifier in the SPS.
  49614. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49615. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49616. */
  49617. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49618. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49619. /**
  49620. * particle global index
  49621. */
  49622. this.idx = 0;
  49623. /**
  49624. * The color of the particle
  49625. */
  49626. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49627. /**
  49628. * The world space position of the particle.
  49629. */
  49630. this.position = BABYLON.Vector3.Zero();
  49631. /**
  49632. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49633. */
  49634. this.rotation = BABYLON.Vector3.Zero();
  49635. /**
  49636. * The scaling of the particle.
  49637. */
  49638. this.scaling = BABYLON.Vector3.One();
  49639. /**
  49640. * The uvs of the particle.
  49641. */
  49642. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49643. /**
  49644. * The current speed of the particle.
  49645. */
  49646. this.velocity = BABYLON.Vector3.Zero();
  49647. /**
  49648. * The pivot point in the particle local space.
  49649. */
  49650. this.pivot = BABYLON.Vector3.Zero();
  49651. /**
  49652. * Is the particle active or not ?
  49653. */
  49654. this.alive = true;
  49655. /**
  49656. * Is the particle visible or not ?
  49657. */
  49658. this.isVisible = true;
  49659. /**
  49660. * Index of this particle in the global "positions" array (Internal use)
  49661. */
  49662. this._pos = 0;
  49663. /**
  49664. * Index of this particle in the global "indices" array (Internal use)
  49665. */
  49666. this._ind = 0;
  49667. /**
  49668. * ModelShape id of this particle
  49669. */
  49670. this.shapeId = 0;
  49671. /**
  49672. * Index of the particle in its shape id (Internal use)
  49673. */
  49674. this.idxInShape = 0;
  49675. /**
  49676. * Still set as invisible in order to skip useless computations (Internal use)
  49677. */
  49678. this._stillInvisible = false;
  49679. /**
  49680. * Last computed particle rotation matrix
  49681. */
  49682. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49683. this.idx = particleIndex;
  49684. this._pos = positionIndex;
  49685. this._ind = indiceIndex;
  49686. this._model = model;
  49687. this.shapeId = shapeId;
  49688. this.idxInShape = idxInShape;
  49689. this._sps = sps;
  49690. if (modelBoundingInfo) {
  49691. this._modelBoundingInfo = modelBoundingInfo;
  49692. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49693. }
  49694. }
  49695. Object.defineProperty(SolidParticle.prototype, "scale", {
  49696. /**
  49697. * Legacy support, changed scale to scaling
  49698. */
  49699. get: function () {
  49700. return this.scaling;
  49701. },
  49702. /**
  49703. * Legacy support, changed scale to scaling
  49704. */
  49705. set: function (scale) {
  49706. this.scaling = scale;
  49707. },
  49708. enumerable: true,
  49709. configurable: true
  49710. });
  49711. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49712. /**
  49713. * Legacy support, changed quaternion to rotationQuaternion
  49714. */
  49715. get: function () {
  49716. return this.rotationQuaternion;
  49717. },
  49718. /**
  49719. * Legacy support, changed quaternion to rotationQuaternion
  49720. */
  49721. set: function (q) {
  49722. this.rotationQuaternion = q;
  49723. },
  49724. enumerable: true,
  49725. configurable: true
  49726. });
  49727. /**
  49728. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49729. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49730. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49731. * @returns true if it intersects
  49732. */
  49733. SolidParticle.prototype.intersectsMesh = function (target) {
  49734. if (!this._boundingInfo || !target._boundingInfo) {
  49735. return false;
  49736. }
  49737. if (this._sps._bSphereOnly) {
  49738. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49739. }
  49740. return this._boundingInfo.intersects(target._boundingInfo, false);
  49741. };
  49742. return SolidParticle;
  49743. }());
  49744. BABYLON.SolidParticle = SolidParticle;
  49745. /**
  49746. * Represents the shape of the model used by one particle of a solid particle system.
  49747. * SPS internal tool, don't use it manually.
  49748. * @see SolidParticleSystem
  49749. */
  49750. var ModelShape = /** @class */ (function () {
  49751. /**
  49752. * 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.
  49753. * SPS internal tool, don't use it manually.
  49754. * @ignore
  49755. */
  49756. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49757. /**
  49758. * length of the shape in the model indices array (internal use)
  49759. */
  49760. this._indicesLength = 0;
  49761. this.shapeID = id;
  49762. this._shape = shape;
  49763. this._indicesLength = indicesLength;
  49764. this._shapeUV = shapeUV;
  49765. this._positionFunction = posFunction;
  49766. this._vertexFunction = vtxFunction;
  49767. }
  49768. return ModelShape;
  49769. }());
  49770. BABYLON.ModelShape = ModelShape;
  49771. /**
  49772. * Represents a Depth Sorted Particle in the solid particle system.
  49773. * @see SolidParticleSystem
  49774. */
  49775. var DepthSortedParticle = /** @class */ (function () {
  49776. function DepthSortedParticle() {
  49777. /**
  49778. * Index of the particle in the "indices" array
  49779. */
  49780. this.ind = 0;
  49781. /**
  49782. * Length of the particle shape in the "indices" array
  49783. */
  49784. this.indicesLength = 0;
  49785. /**
  49786. * Squared distance from the particle to the camera
  49787. */
  49788. this.sqDistance = 0.0;
  49789. }
  49790. return DepthSortedParticle;
  49791. }());
  49792. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49793. })(BABYLON || (BABYLON = {}));
  49794. //# sourceMappingURL=babylon.solidParticle.js.map
  49795. var BABYLON;
  49796. (function (BABYLON) {
  49797. /**
  49798. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49799. *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.
  49800. * The SPS is also a particle system. It provides some methods to manage the particles.
  49801. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49802. *
  49803. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49804. */
  49805. var SolidParticleSystem = /** @class */ (function () {
  49806. /**
  49807. * Creates a SPS (Solid Particle System) object.
  49808. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49809. * @param scene (Scene) is the scene in which the SPS is added.
  49810. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49811. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49812. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49813. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49814. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49815. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49816. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49817. */
  49818. function SolidParticleSystem(name, scene, options) {
  49819. /**
  49820. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49821. * Example : var p = SPS.particles[i];
  49822. */
  49823. this.particles = new Array();
  49824. /**
  49825. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49826. */
  49827. this.nbParticles = 0;
  49828. /**
  49829. * If the particles must ever face the camera (default false). Useful for planar particles.
  49830. */
  49831. this.billboard = false;
  49832. /**
  49833. * Recompute normals when adding a shape
  49834. */
  49835. this.recomputeNormals = true;
  49836. /**
  49837. * This a counter ofr your own usage. It's not set by any SPS functions.
  49838. */
  49839. this.counter = 0;
  49840. /**
  49841. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49842. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49843. */
  49844. this.vars = {};
  49845. /**
  49846. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49847. */
  49848. this._bSphereOnly = false;
  49849. /**
  49850. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49851. */
  49852. this._bSphereRadiusFactor = 1.0;
  49853. this._positions = new Array();
  49854. this._indices = new Array();
  49855. this._normals = new Array();
  49856. this._colors = new Array();
  49857. this._uvs = new Array();
  49858. this._index = 0; // indices index
  49859. this._updatable = true;
  49860. this._pickable = false;
  49861. this._isVisibilityBoxLocked = false;
  49862. this._alwaysVisible = false;
  49863. this._depthSort = false;
  49864. this._shapeCounter = 0;
  49865. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49866. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49867. this._computeParticleColor = true;
  49868. this._computeParticleTexture = true;
  49869. this._computeParticleRotation = true;
  49870. this._computeParticleVertex = false;
  49871. this._computeBoundingBox = false;
  49872. this._depthSortParticles = true;
  49873. this._cam_axisZ = BABYLON.Vector3.Zero();
  49874. this._cam_axisY = BABYLON.Vector3.Zero();
  49875. this._cam_axisX = BABYLON.Vector3.Zero();
  49876. this._axisZ = BABYLON.Axis.Z;
  49877. this._camDir = BABYLON.Vector3.Zero();
  49878. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49879. this._rotMatrix = new BABYLON.Matrix();
  49880. this._invertMatrix = new BABYLON.Matrix();
  49881. this._rotated = BABYLON.Vector3.Zero();
  49882. this._quaternion = new BABYLON.Quaternion();
  49883. this._vertex = BABYLON.Vector3.Zero();
  49884. this._normal = BABYLON.Vector3.Zero();
  49885. this._yaw = 0.0;
  49886. this._pitch = 0.0;
  49887. this._roll = 0.0;
  49888. this._halfroll = 0.0;
  49889. this._halfpitch = 0.0;
  49890. this._halfyaw = 0.0;
  49891. this._sinRoll = 0.0;
  49892. this._cosRoll = 0.0;
  49893. this._sinPitch = 0.0;
  49894. this._cosPitch = 0.0;
  49895. this._sinYaw = 0.0;
  49896. this._cosYaw = 0.0;
  49897. this._mustUnrotateFixedNormals = false;
  49898. this._minimum = BABYLON.Tmp.Vector3[0];
  49899. this._maximum = BABYLON.Tmp.Vector3[1];
  49900. this._minBbox = BABYLON.Tmp.Vector3[4];
  49901. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49902. this._particlesIntersect = false;
  49903. this._depthSortFunction = function (p1, p2) {
  49904. return (p2.sqDistance - p1.sqDistance);
  49905. };
  49906. this._needs32Bits = false;
  49907. this.name = name;
  49908. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49909. this._camera = scene.activeCamera;
  49910. this._pickable = options ? options.isPickable : false;
  49911. this._depthSort = options ? options.enableDepthSort : false;
  49912. this._particlesIntersect = options ? options.particleIntersection : false;
  49913. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49914. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49915. if (options && options.updatable) {
  49916. this._updatable = options.updatable;
  49917. }
  49918. else {
  49919. this._updatable = true;
  49920. }
  49921. if (this._pickable) {
  49922. this.pickedParticles = [];
  49923. }
  49924. if (this._depthSort) {
  49925. this.depthSortedParticles = [];
  49926. }
  49927. }
  49928. /**
  49929. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49930. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49931. * @returns the created mesh
  49932. */
  49933. SolidParticleSystem.prototype.buildMesh = function () {
  49934. if (this.nbParticles === 0) {
  49935. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49936. this.addShape(triangle, 1);
  49937. triangle.dispose();
  49938. }
  49939. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49940. this._positions32 = new Float32Array(this._positions);
  49941. this._uvs32 = new Float32Array(this._uvs);
  49942. this._colors32 = new Float32Array(this._colors);
  49943. if (this.recomputeNormals) {
  49944. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49945. }
  49946. this._normals32 = new Float32Array(this._normals);
  49947. this._fixedNormal32 = new Float32Array(this._normals);
  49948. if (this._mustUnrotateFixedNormals) {
  49949. this._unrotateFixedNormals();
  49950. }
  49951. var vertexData = new BABYLON.VertexData();
  49952. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49953. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49954. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49955. if (this._uvs32) {
  49956. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49957. ;
  49958. }
  49959. if (this._colors32) {
  49960. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49961. }
  49962. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49963. vertexData.applyToMesh(mesh, this._updatable);
  49964. this.mesh = mesh;
  49965. this.mesh.isPickable = this._pickable;
  49966. // free memory
  49967. if (!this._depthSort) {
  49968. this._indices = null;
  49969. }
  49970. this._positions = null;
  49971. this._normals = null;
  49972. this._uvs = null;
  49973. this._colors = null;
  49974. if (!this._updatable) {
  49975. this.particles.length = 0;
  49976. }
  49977. return mesh;
  49978. };
  49979. /**
  49980. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49981. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49982. * Thus the particles generated from `digest()` have their property `position` set yet.
  49983. * @param mesh ( Mesh ) is the mesh to be digested
  49984. * @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
  49985. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49986. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49987. * @returns the current SPS
  49988. */
  49989. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49990. var size = (options && options.facetNb) || 1;
  49991. var number = (options && options.number) || 0;
  49992. var delta = (options && options.delta) || 0;
  49993. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49994. var meshInd = mesh.getIndices();
  49995. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49996. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49997. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49998. var f = 0; // facet counter
  49999. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  50000. // compute size from number
  50001. if (number) {
  50002. number = (number > totalFacets) ? totalFacets : number;
  50003. size = Math.round(totalFacets / number);
  50004. delta = 0;
  50005. }
  50006. else {
  50007. size = (size > totalFacets) ? totalFacets : size;
  50008. }
  50009. var facetPos = []; // submesh positions
  50010. var facetInd = []; // submesh indices
  50011. var facetUV = []; // submesh UV
  50012. var facetCol = []; // submesh colors
  50013. var barycenter = BABYLON.Tmp.Vector3[0];
  50014. var sizeO = size;
  50015. while (f < totalFacets) {
  50016. size = sizeO + Math.floor((1 + delta) * Math.random());
  50017. if (f > totalFacets - size) {
  50018. size = totalFacets - f;
  50019. }
  50020. // reset temp arrays
  50021. facetPos.length = 0;
  50022. facetInd.length = 0;
  50023. facetUV.length = 0;
  50024. facetCol.length = 0;
  50025. // iterate over "size" facets
  50026. var fi = 0;
  50027. for (var j = f * 3; j < (f + size) * 3; j++) {
  50028. facetInd.push(fi);
  50029. var i = meshInd[j];
  50030. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  50031. if (meshUV) {
  50032. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  50033. }
  50034. if (meshCol) {
  50035. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  50036. }
  50037. fi++;
  50038. }
  50039. // create a model shape for each single particle
  50040. var idx = this.nbParticles;
  50041. var shape = this._posToShape(facetPos);
  50042. var shapeUV = this._uvsToShapeUV(facetUV);
  50043. // compute the barycenter of the shape
  50044. var v;
  50045. for (v = 0; v < shape.length; v++) {
  50046. barycenter.addInPlace(shape[v]);
  50047. }
  50048. barycenter.scaleInPlace(1 / shape.length);
  50049. // shift the shape from its barycenter to the origin
  50050. for (v = 0; v < shape.length; v++) {
  50051. shape[v].subtractInPlace(barycenter);
  50052. }
  50053. var bInfo;
  50054. if (this._particlesIntersect) {
  50055. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  50056. }
  50057. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  50058. // add the particle in the SPS
  50059. var currentPos = this._positions.length;
  50060. var currentInd = this._indices.length;
  50061. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  50062. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  50063. // initialize the particle position
  50064. this.particles[this.nbParticles].position.addInPlace(barycenter);
  50065. this._index += shape.length;
  50066. idx++;
  50067. this.nbParticles++;
  50068. this._shapeCounter++;
  50069. f += size;
  50070. }
  50071. return this;
  50072. };
  50073. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  50074. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  50075. var index = 0;
  50076. var idx = 0;
  50077. for (var p = 0; p < this.particles.length; p++) {
  50078. this._particle = this.particles[p];
  50079. this._shape = this._particle._model._shape;
  50080. if (this._particle.rotationQuaternion) {
  50081. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50082. }
  50083. else {
  50084. this._yaw = this._particle.rotation.y;
  50085. this._pitch = this._particle.rotation.x;
  50086. this._roll = this._particle.rotation.z;
  50087. this._quaternionRotationYPR();
  50088. }
  50089. this._quaternionToRotationMatrix();
  50090. this._rotMatrix.invertToRef(this._invertMatrix);
  50091. for (var pt = 0; pt < this._shape.length; pt++) {
  50092. idx = index + pt * 3;
  50093. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  50094. this._fixedNormal32[idx] = this._normal.x;
  50095. this._fixedNormal32[idx + 1] = this._normal.y;
  50096. this._fixedNormal32[idx + 2] = this._normal.z;
  50097. }
  50098. index = idx + 3;
  50099. }
  50100. };
  50101. //reset copy
  50102. SolidParticleSystem.prototype._resetCopy = function () {
  50103. this._copy.position.x = 0;
  50104. this._copy.position.y = 0;
  50105. this._copy.position.z = 0;
  50106. this._copy.rotation.x = 0;
  50107. this._copy.rotation.y = 0;
  50108. this._copy.rotation.z = 0;
  50109. this._copy.rotationQuaternion = null;
  50110. this._copy.scaling.x = 1.0;
  50111. this._copy.scaling.y = 1.0;
  50112. this._copy.scaling.z = 1.0;
  50113. this._copy.uvs.x = 0;
  50114. this._copy.uvs.y = 0;
  50115. this._copy.uvs.z = 1.0;
  50116. this._copy.uvs.w = 1.0;
  50117. this._copy.color = null;
  50118. };
  50119. // _meshBuilder : inserts the shape model in the global SPS mesh
  50120. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  50121. var i;
  50122. var u = 0;
  50123. var c = 0;
  50124. var n = 0;
  50125. this._resetCopy();
  50126. if (options && options.positionFunction) {
  50127. options.positionFunction(this._copy, idx, idxInShape);
  50128. this._mustUnrotateFixedNormals = true;
  50129. }
  50130. if (this._copy.rotationQuaternion) {
  50131. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50132. }
  50133. else {
  50134. this._yaw = this._copy.rotation.y;
  50135. this._pitch = this._copy.rotation.x;
  50136. this._roll = this._copy.rotation.z;
  50137. this._quaternionRotationYPR();
  50138. }
  50139. this._quaternionToRotationMatrix();
  50140. for (i = 0; i < shape.length; i++) {
  50141. this._vertex.x = shape[i].x;
  50142. this._vertex.y = shape[i].y;
  50143. this._vertex.z = shape[i].z;
  50144. if (options && options.vertexFunction) {
  50145. options.vertexFunction(this._copy, this._vertex, i);
  50146. }
  50147. this._vertex.x *= this._copy.scaling.x;
  50148. this._vertex.y *= this._copy.scaling.y;
  50149. this._vertex.z *= this._copy.scaling.z;
  50150. this._vertex.x += this._copy.pivot.x;
  50151. this._vertex.y += this._copy.pivot.y;
  50152. this._vertex.z += this._copy.pivot.z;
  50153. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50154. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50155. if (meshUV) {
  50156. 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);
  50157. u += 2;
  50158. }
  50159. if (this._copy.color) {
  50160. this._color = this._copy.color;
  50161. }
  50162. else if (meshCol && meshCol[c] !== undefined) {
  50163. this._color.r = meshCol[c];
  50164. this._color.g = meshCol[c + 1];
  50165. this._color.b = meshCol[c + 2];
  50166. this._color.a = meshCol[c + 3];
  50167. }
  50168. else {
  50169. this._color.r = 1.0;
  50170. this._color.g = 1.0;
  50171. this._color.b = 1.0;
  50172. this._color.a = 1.0;
  50173. }
  50174. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50175. c += 4;
  50176. if (!this.recomputeNormals && meshNor) {
  50177. this._normal.x = meshNor[n];
  50178. this._normal.y = meshNor[n + 1];
  50179. this._normal.z = meshNor[n + 2];
  50180. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  50181. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50182. n += 3;
  50183. }
  50184. }
  50185. for (i = 0; i < meshInd.length; i++) {
  50186. var current_ind = p + meshInd[i];
  50187. indices.push(current_ind);
  50188. if (current_ind > 65535) {
  50189. this._needs32Bits = true;
  50190. }
  50191. }
  50192. if (this._pickable) {
  50193. var nbfaces = meshInd.length / 3;
  50194. for (i = 0; i < nbfaces; i++) {
  50195. this.pickedParticles.push({ idx: idx, faceId: i });
  50196. }
  50197. }
  50198. if (this._depthSort) {
  50199. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  50200. }
  50201. return this._copy;
  50202. };
  50203. // returns a shape array from positions array
  50204. SolidParticleSystem.prototype._posToShape = function (positions) {
  50205. var shape = [];
  50206. for (var i = 0; i < positions.length; i += 3) {
  50207. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50208. }
  50209. return shape;
  50210. };
  50211. // returns a shapeUV array from a Vector4 uvs
  50212. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50213. var shapeUV = [];
  50214. if (uvs) {
  50215. for (var i = 0; i < uvs.length; i++)
  50216. shapeUV.push(uvs[i]);
  50217. }
  50218. return shapeUV;
  50219. };
  50220. // adds a new particle object in the particles array
  50221. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  50222. if (bInfo === void 0) { bInfo = null; }
  50223. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  50224. this.particles.push(sp);
  50225. return sp;
  50226. };
  50227. /**
  50228. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50229. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50230. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  50231. * @param nb (positive integer) the number of particles to be created from this model
  50232. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  50233. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  50234. * @returns the number of shapes in the system
  50235. */
  50236. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50237. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50238. var meshInd = mesh.getIndices();
  50239. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50240. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50241. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50242. var bbInfo;
  50243. if (this._particlesIntersect) {
  50244. bbInfo = mesh.getBoundingInfo();
  50245. }
  50246. var shape = this._posToShape(meshPos);
  50247. var shapeUV = this._uvsToShapeUV(meshUV);
  50248. var posfunc = options ? options.positionFunction : null;
  50249. var vtxfunc = options ? options.vertexFunction : null;
  50250. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50251. // particles
  50252. var sp;
  50253. var currentCopy;
  50254. var idx = this.nbParticles;
  50255. for (var i = 0; i < nb; i++) {
  50256. var currentPos = this._positions.length;
  50257. var currentInd = this._indices.length;
  50258. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50259. if (this._updatable) {
  50260. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50261. sp.position.copyFrom(currentCopy.position);
  50262. sp.rotation.copyFrom(currentCopy.rotation);
  50263. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50264. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50265. }
  50266. if (currentCopy.color && sp.color) {
  50267. sp.color.copyFrom(currentCopy.color);
  50268. }
  50269. sp.scaling.copyFrom(currentCopy.scaling);
  50270. sp.uvs.copyFrom(currentCopy.uvs);
  50271. }
  50272. this._index += shape.length;
  50273. idx++;
  50274. }
  50275. this.nbParticles += nb;
  50276. this._shapeCounter++;
  50277. return this._shapeCounter - 1;
  50278. };
  50279. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50280. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50281. this._resetCopy();
  50282. if (particle._model._positionFunction) {
  50283. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50284. }
  50285. if (this._copy.rotationQuaternion) {
  50286. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50287. }
  50288. else {
  50289. this._yaw = this._copy.rotation.y;
  50290. this._pitch = this._copy.rotation.x;
  50291. this._roll = this._copy.rotation.z;
  50292. this._quaternionRotationYPR();
  50293. }
  50294. this._quaternionToRotationMatrix();
  50295. this._shape = particle._model._shape;
  50296. for (var pt = 0; pt < this._shape.length; pt++) {
  50297. this._vertex.x = this._shape[pt].x;
  50298. this._vertex.y = this._shape[pt].y;
  50299. this._vertex.z = this._shape[pt].z;
  50300. if (particle._model._vertexFunction) {
  50301. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50302. }
  50303. this._vertex.x *= this._copy.scaling.x;
  50304. this._vertex.y *= this._copy.scaling.y;
  50305. this._vertex.z *= this._copy.scaling.z;
  50306. this._vertex.x += this._copy.pivot.x;
  50307. this._vertex.y += this._copy.pivot.y;
  50308. this._vertex.z += this._copy.pivot.z;
  50309. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50310. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50311. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50312. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50313. }
  50314. particle.position.x = 0.0;
  50315. particle.position.y = 0.0;
  50316. particle.position.z = 0.0;
  50317. particle.rotation.x = 0.0;
  50318. particle.rotation.y = 0.0;
  50319. particle.rotation.z = 0.0;
  50320. particle.rotationQuaternion = null;
  50321. particle.scaling.x = 1.0;
  50322. particle.scaling.y = 1.0;
  50323. particle.scaling.z = 1.0;
  50324. };
  50325. /**
  50326. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50327. * @returns the SPS.
  50328. */
  50329. SolidParticleSystem.prototype.rebuildMesh = function () {
  50330. for (var p = 0; p < this.particles.length; p++) {
  50331. this._rebuildParticle(this.particles[p]);
  50332. }
  50333. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50334. return this;
  50335. };
  50336. /**
  50337. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50338. * This method calls `updateParticle()` for each particle of the SPS.
  50339. * For an animated SPS, it is usually called within the render loop.
  50340. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50341. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50342. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50343. * @returns the SPS.
  50344. */
  50345. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50346. if (start === void 0) { start = 0; }
  50347. if (end === void 0) { end = this.nbParticles - 1; }
  50348. if (update === void 0) { update = true; }
  50349. if (!this._updatable) {
  50350. return this;
  50351. }
  50352. // custom beforeUpdate
  50353. this.beforeUpdateParticles(start, end, update);
  50354. this._cam_axisX.x = 1.0;
  50355. this._cam_axisX.y = 0.0;
  50356. this._cam_axisX.z = 0.0;
  50357. this._cam_axisY.x = 0.0;
  50358. this._cam_axisY.y = 1.0;
  50359. this._cam_axisY.z = 0.0;
  50360. this._cam_axisZ.x = 0.0;
  50361. this._cam_axisZ.y = 0.0;
  50362. this._cam_axisZ.z = 1.0;
  50363. // cases when the World Matrix is to be computed first
  50364. if (this.billboard || this._depthSort) {
  50365. this.mesh.computeWorldMatrix(true);
  50366. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50367. }
  50368. // if the particles will always face the camera
  50369. if (this.billboard) {
  50370. // compute the camera position and un-rotate it by the current mesh rotation
  50371. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50372. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50373. this._cam_axisZ.normalize();
  50374. // same for camera up vector extracted from the cam view matrix
  50375. var view = this._camera.getViewMatrix(true);
  50376. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50377. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50378. this._cam_axisY.normalize();
  50379. this._cam_axisX.normalize();
  50380. }
  50381. // if depthSort, compute the camera global position in the mesh local system
  50382. if (this._depthSort) {
  50383. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50384. }
  50385. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50386. var idx = 0; // current position index in the global array positions32
  50387. var index = 0; // position start index in the global array positions32 of the current particle
  50388. var colidx = 0; // current color index in the global array colors32
  50389. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50390. var uvidx = 0; // current uv index in the global array uvs32
  50391. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50392. var pt = 0; // current index in the particle model shape
  50393. if (this.mesh.isFacetDataEnabled) {
  50394. this._computeBoundingBox = true;
  50395. }
  50396. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50397. if (this._computeBoundingBox) {
  50398. if (start == 0 && end == this.nbParticles - 1) {
  50399. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50400. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50401. }
  50402. else {
  50403. if (this.mesh._boundingInfo) {
  50404. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50405. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50406. }
  50407. }
  50408. }
  50409. // particle loop
  50410. index = this.particles[start]._pos;
  50411. var vpos = (index / 3) | 0;
  50412. colorIndex = vpos * 4;
  50413. uvIndex = vpos * 2;
  50414. for (var p = start; p <= end; p++) {
  50415. this._particle = this.particles[p];
  50416. this._shape = this._particle._model._shape;
  50417. this._shapeUV = this._particle._model._shapeUV;
  50418. // call to custom user function to update the particle properties
  50419. this.updateParticle(this._particle);
  50420. // camera-particle distance for depth sorting
  50421. if (this._depthSort && this._depthSortParticles) {
  50422. var dsp = this.depthSortedParticles[p];
  50423. dsp.ind = this._particle._ind;
  50424. dsp.indicesLength = this._particle._model._indicesLength;
  50425. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50426. }
  50427. // skip the computations for inactive or already invisible particles
  50428. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50429. // increment indexes for the next particle
  50430. pt = this._shape.length;
  50431. index += pt * 3;
  50432. colorIndex += pt * 4;
  50433. uvIndex += pt * 2;
  50434. continue;
  50435. }
  50436. if (this._particle.isVisible) {
  50437. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50438. // particle rotation matrix
  50439. if (this.billboard) {
  50440. this._particle.rotation.x = 0.0;
  50441. this._particle.rotation.y = 0.0;
  50442. }
  50443. if (this._computeParticleRotation || this.billboard) {
  50444. if (this._particle.rotationQuaternion) {
  50445. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50446. }
  50447. else {
  50448. this._yaw = this._particle.rotation.y;
  50449. this._pitch = this._particle.rotation.x;
  50450. this._roll = this._particle.rotation.z;
  50451. this._quaternionRotationYPR();
  50452. }
  50453. this._quaternionToRotationMatrix();
  50454. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50455. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50456. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50457. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50458. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50459. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50460. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50461. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50462. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50463. }
  50464. // particle vertex loop
  50465. for (pt = 0; pt < this._shape.length; pt++) {
  50466. idx = index + pt * 3;
  50467. colidx = colorIndex + pt * 4;
  50468. uvidx = uvIndex + pt * 2;
  50469. this._vertex.x = this._shape[pt].x;
  50470. this._vertex.y = this._shape[pt].y;
  50471. this._vertex.z = this._shape[pt].z;
  50472. if (this._computeParticleVertex) {
  50473. this.updateParticleVertex(this._particle, this._vertex, pt);
  50474. }
  50475. // positions
  50476. this._vertex.x *= this._particle.scaling.x;
  50477. this._vertex.y *= this._particle.scaling.y;
  50478. this._vertex.z *= this._particle.scaling.z;
  50479. this._vertex.x += this._particle.pivot.x;
  50480. this._vertex.y += this._particle.pivot.y;
  50481. this._vertex.z += this._particle.pivot.z;
  50482. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50483. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50484. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50485. this._positions32[idx] = 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;
  50486. this._positions32[idx + 1] = 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;
  50487. this._positions32[idx + 2] = 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;
  50488. if (this._computeBoundingBox) {
  50489. if (this._positions32[idx] < this._minimum.x) {
  50490. this._minimum.x = this._positions32[idx];
  50491. }
  50492. if (this._positions32[idx] > this._maximum.x) {
  50493. this._maximum.x = this._positions32[idx];
  50494. }
  50495. if (this._positions32[idx + 1] < this._minimum.y) {
  50496. this._minimum.y = this._positions32[idx + 1];
  50497. }
  50498. if (this._positions32[idx + 1] > this._maximum.y) {
  50499. this._maximum.y = this._positions32[idx + 1];
  50500. }
  50501. if (this._positions32[idx + 2] < this._minimum.z) {
  50502. this._minimum.z = this._positions32[idx + 2];
  50503. }
  50504. if (this._positions32[idx + 2] > this._maximum.z) {
  50505. this._maximum.z = this._positions32[idx + 2];
  50506. }
  50507. }
  50508. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50509. if (!this._computeParticleVertex) {
  50510. this._normal.x = this._fixedNormal32[idx];
  50511. this._normal.y = this._fixedNormal32[idx + 1];
  50512. this._normal.z = this._fixedNormal32[idx + 2];
  50513. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50514. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50515. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50516. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50517. 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;
  50518. 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;
  50519. }
  50520. if (this._computeParticleColor && this._particle.color) {
  50521. this._colors32[colidx] = this._particle.color.r;
  50522. this._colors32[colidx + 1] = this._particle.color.g;
  50523. this._colors32[colidx + 2] = this._particle.color.b;
  50524. this._colors32[colidx + 3] = this._particle.color.a;
  50525. }
  50526. if (this._computeParticleTexture) {
  50527. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50528. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50529. }
  50530. }
  50531. }
  50532. else {
  50533. this._particle._stillInvisible = true; // mark the particle as invisible
  50534. for (pt = 0; pt < this._shape.length; pt++) {
  50535. idx = index + pt * 3;
  50536. colidx = colorIndex + pt * 4;
  50537. uvidx = uvIndex + pt * 2;
  50538. this._positions32[idx] = 0.0;
  50539. this._positions32[idx + 1] = 0.0;
  50540. this._positions32[idx + 2] = 0.0;
  50541. this._normals32[idx] = 0.0;
  50542. this._normals32[idx + 1] = 0.0;
  50543. this._normals32[idx + 2] = 0.0;
  50544. if (this._computeParticleColor && this._particle.color) {
  50545. this._colors32[colidx] = this._particle.color.r;
  50546. this._colors32[colidx + 1] = this._particle.color.g;
  50547. this._colors32[colidx + 2] = this._particle.color.b;
  50548. this._colors32[colidx + 3] = this._particle.color.a;
  50549. }
  50550. if (this._computeParticleTexture) {
  50551. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50552. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50553. }
  50554. }
  50555. }
  50556. // if the particle intersections must be computed : update the bbInfo
  50557. if (this._particlesIntersect) {
  50558. var bInfo = this._particle._boundingInfo;
  50559. var bBox = bInfo.boundingBox;
  50560. var bSphere = bInfo.boundingSphere;
  50561. if (!this._bSphereOnly) {
  50562. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50563. for (var b = 0; b < bBox.vectors.length; b++) {
  50564. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50565. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50566. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50567. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50568. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50569. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50570. 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;
  50571. 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;
  50572. 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;
  50573. }
  50574. bBox._update(this.mesh._worldMatrix);
  50575. }
  50576. // place and scale the particle bouding sphere in the SPS local system, then update it
  50577. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50578. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50579. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50580. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50581. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50582. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50583. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50584. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50585. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50586. 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));
  50587. bSphere._update(this.mesh._worldMatrix);
  50588. }
  50589. // increment indexes for the next particle
  50590. index = idx + 3;
  50591. colorIndex = colidx + 4;
  50592. uvIndex = uvidx + 2;
  50593. }
  50594. // if the VBO must be updated
  50595. if (update) {
  50596. if (this._computeParticleColor) {
  50597. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50598. }
  50599. if (this._computeParticleTexture) {
  50600. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50601. }
  50602. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50603. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50604. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50605. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50606. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50607. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50608. for (var i = 0; i < this._normals32.length; i++) {
  50609. this._fixedNormal32[i] = this._normals32[i];
  50610. }
  50611. }
  50612. if (!this.mesh.areNormalsFrozen) {
  50613. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50614. }
  50615. }
  50616. if (this._depthSort && this._depthSortParticles) {
  50617. this.depthSortedParticles.sort(this._depthSortFunction);
  50618. var dspl = this.depthSortedParticles.length;
  50619. var sorted = 0;
  50620. var lind = 0;
  50621. var sind = 0;
  50622. var sid = 0;
  50623. for (sorted = 0; sorted < dspl; sorted++) {
  50624. lind = this.depthSortedParticles[sorted].indicesLength;
  50625. sind = this.depthSortedParticles[sorted].ind;
  50626. for (var i = 0; i < lind; i++) {
  50627. this._indices32[sid] = this._indices[sind + i];
  50628. sid++;
  50629. }
  50630. }
  50631. this.mesh.updateIndices(this._indices32);
  50632. }
  50633. }
  50634. if (this._computeBoundingBox) {
  50635. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50636. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50637. }
  50638. this.afterUpdateParticles(start, end, update);
  50639. return this;
  50640. };
  50641. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50642. this._halfroll = this._roll * 0.5;
  50643. this._halfpitch = this._pitch * 0.5;
  50644. this._halfyaw = this._yaw * 0.5;
  50645. this._sinRoll = Math.sin(this._halfroll);
  50646. this._cosRoll = Math.cos(this._halfroll);
  50647. this._sinPitch = Math.sin(this._halfpitch);
  50648. this._cosPitch = Math.cos(this._halfpitch);
  50649. this._sinYaw = Math.sin(this._halfyaw);
  50650. this._cosYaw = Math.cos(this._halfyaw);
  50651. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50652. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50653. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50654. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50655. };
  50656. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50657. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50658. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50659. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50660. this._rotMatrix.m[3] = 0;
  50661. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50662. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50663. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50664. this._rotMatrix.m[7] = 0;
  50665. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50666. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50667. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50668. this._rotMatrix.m[11] = 0;
  50669. this._rotMatrix.m[12] = 0;
  50670. this._rotMatrix.m[13] = 0;
  50671. this._rotMatrix.m[14] = 0;
  50672. this._rotMatrix.m[15] = 1.0;
  50673. };
  50674. /**
  50675. * Disposes the SPS.
  50676. */
  50677. SolidParticleSystem.prototype.dispose = function () {
  50678. this.mesh.dispose();
  50679. this.vars = null;
  50680. // drop references to internal big arrays for the GC
  50681. this._positions = null;
  50682. this._indices = null;
  50683. this._normals = null;
  50684. this._uvs = null;
  50685. this._colors = null;
  50686. this._indices32 = null;
  50687. this._positions32 = null;
  50688. this._normals32 = null;
  50689. this._fixedNormal32 = null;
  50690. this._uvs32 = null;
  50691. this._colors32 = null;
  50692. this.pickedParticles = null;
  50693. };
  50694. /**
  50695. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50697. * @returns the SPS.
  50698. */
  50699. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50700. if (!this._isVisibilityBoxLocked) {
  50701. this.mesh.refreshBoundingInfo();
  50702. }
  50703. return this;
  50704. };
  50705. /**
  50706. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50707. * @param size the size (float) of the visibility box
  50708. * note : this doesn't lock the SPS mesh bounding box.
  50709. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50710. */
  50711. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50712. var vis = size / 2;
  50713. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50714. };
  50715. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50716. /**
  50717. * Gets whether the SPS as always visible or not
  50718. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50719. */
  50720. get: function () {
  50721. return this._alwaysVisible;
  50722. },
  50723. /**
  50724. * Sets the SPS as always visible or not
  50725. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50726. */
  50727. set: function (val) {
  50728. this._alwaysVisible = val;
  50729. this.mesh.alwaysSelectAsActiveMesh = val;
  50730. },
  50731. enumerable: true,
  50732. configurable: true
  50733. });
  50734. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50735. /**
  50736. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50737. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50738. */
  50739. get: function () {
  50740. return this._isVisibilityBoxLocked;
  50741. },
  50742. /**
  50743. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50744. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50745. */
  50746. set: function (val) {
  50747. this._isVisibilityBoxLocked = val;
  50748. var boundingInfo = this.mesh.getBoundingInfo();
  50749. boundingInfo.isLocked = val;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50755. /**
  50756. * Gets if `setParticles()` computes the particle rotations or not.
  50757. * Default value : true. The SPS is faster when it's set to false.
  50758. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50759. */
  50760. get: function () {
  50761. return this._computeParticleRotation;
  50762. },
  50763. /**
  50764. * Tells to `setParticles()` to compute the particle rotations or not.
  50765. * Default value : true. The SPS is faster when it's set to false.
  50766. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50767. */
  50768. set: function (val) {
  50769. this._computeParticleRotation = val;
  50770. },
  50771. enumerable: true,
  50772. configurable: true
  50773. });
  50774. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50775. /**
  50776. * Gets if `setParticles()` computes the particle colors or not.
  50777. * Default value : true. The SPS is faster when it's set to false.
  50778. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50779. */
  50780. get: function () {
  50781. return this._computeParticleColor;
  50782. },
  50783. /**
  50784. * Tells to `setParticles()` to compute the particle colors or not.
  50785. * Default value : true. The SPS is faster when it's set to false.
  50786. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50787. */
  50788. set: function (val) {
  50789. this._computeParticleColor = val;
  50790. },
  50791. enumerable: true,
  50792. configurable: true
  50793. });
  50794. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50795. /**
  50796. * Gets if `setParticles()` computes the particle textures or not.
  50797. * Default value : true. The SPS is faster when it's set to false.
  50798. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50799. */
  50800. get: function () {
  50801. return this._computeParticleTexture;
  50802. },
  50803. set: function (val) {
  50804. this._computeParticleTexture = val;
  50805. },
  50806. enumerable: true,
  50807. configurable: true
  50808. });
  50809. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50810. /**
  50811. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50812. * Default value : false. The SPS is faster when it's set to false.
  50813. * Note : the particle custom vertex positions aren't stored values.
  50814. */
  50815. get: function () {
  50816. return this._computeParticleVertex;
  50817. },
  50818. /**
  50819. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50820. * Default value : false. The SPS is faster when it's set to false.
  50821. * Note : the particle custom vertex positions aren't stored values.
  50822. */
  50823. set: function (val) {
  50824. this._computeParticleVertex = val;
  50825. },
  50826. enumerable: true,
  50827. configurable: true
  50828. });
  50829. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50830. /**
  50831. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50832. */
  50833. get: function () {
  50834. return this._computeBoundingBox;
  50835. },
  50836. /**
  50837. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50838. */
  50839. set: function (val) {
  50840. this._computeBoundingBox = val;
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50846. /**
  50847. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50848. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50849. * Default : `true`
  50850. */
  50851. get: function () {
  50852. return this._depthSortParticles;
  50853. },
  50854. /**
  50855. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50856. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50857. * Default : `true`
  50858. */
  50859. set: function (val) {
  50860. this._depthSortParticles = val;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. // =======================================================================
  50866. // Particle behavior logic
  50867. // these following methods may be overwritten by the user to fit his needs
  50868. /**
  50869. * This function does nothing. It may be overwritten to set all the particle first values.
  50870. * The SPS doesn't call this function, you may have to call it by your own.
  50871. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50872. */
  50873. SolidParticleSystem.prototype.initParticles = function () {
  50874. };
  50875. /**
  50876. * This function does nothing. It may be overwritten to recycle a particle.
  50877. * The SPS doesn't call this function, you may have to call it by your own.
  50878. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50879. * @param particle The particle to recycle
  50880. * @returns the recycled particle
  50881. */
  50882. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50883. return particle;
  50884. };
  50885. /**
  50886. * Updates a particle : this function should be overwritten by the user.
  50887. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50888. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50889. * @example : just set a particle position or velocity and recycle conditions
  50890. * @param particle The particle to update
  50891. * @returns the updated particle
  50892. */
  50893. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50894. return particle;
  50895. };
  50896. /**
  50897. * Updates a vertex of a particle : it can be overwritten by the user.
  50898. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50899. * @param particle the current particle
  50900. * @param vertex the current index of the current particle
  50901. * @param pt the index of the current vertex in the particle shape
  50902. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50903. * @example : just set a vertex particle position
  50904. * @returns the updated vertex
  50905. */
  50906. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50907. return vertex;
  50908. };
  50909. /**
  50910. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50911. * This does nothing and may be overwritten by the user.
  50912. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50913. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50914. * @param update the boolean update value actually passed to setParticles()
  50915. */
  50916. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50917. };
  50918. /**
  50919. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50920. * This will be passed three parameters.
  50921. * This does nothing and may be overwritten by the user.
  50922. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50923. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50924. * @param update the boolean update value actually passed to setParticles()
  50925. */
  50926. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50927. };
  50928. return SolidParticleSystem;
  50929. }());
  50930. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50931. })(BABYLON || (BABYLON = {}));
  50932. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50933. var BABYLON;
  50934. (function (BABYLON) {
  50935. var ShaderMaterial = /** @class */ (function (_super) {
  50936. __extends(ShaderMaterial, _super);
  50937. function ShaderMaterial(name, scene, shaderPath, options) {
  50938. var _this = _super.call(this, name, scene) || this;
  50939. _this._textures = {};
  50940. _this._textureArrays = {};
  50941. _this._floats = {};
  50942. _this._ints = {};
  50943. _this._floatsArrays = {};
  50944. _this._colors3 = {};
  50945. _this._colors3Arrays = {};
  50946. _this._colors4 = {};
  50947. _this._vectors2 = {};
  50948. _this._vectors3 = {};
  50949. _this._vectors4 = {};
  50950. _this._matrices = {};
  50951. _this._matrices3x3 = {};
  50952. _this._matrices2x2 = {};
  50953. _this._vectors2Arrays = {};
  50954. _this._vectors3Arrays = {};
  50955. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50956. _this._shaderPath = shaderPath;
  50957. options.needAlphaBlending = options.needAlphaBlending || false;
  50958. options.needAlphaTesting = options.needAlphaTesting || false;
  50959. options.attributes = options.attributes || ["position", "normal", "uv"];
  50960. options.uniforms = options.uniforms || ["worldViewProjection"];
  50961. options.uniformBuffers = options.uniformBuffers || [];
  50962. options.samplers = options.samplers || [];
  50963. options.defines = options.defines || [];
  50964. _this._options = options;
  50965. return _this;
  50966. }
  50967. ShaderMaterial.prototype.getClassName = function () {
  50968. return "ShaderMaterial";
  50969. };
  50970. ShaderMaterial.prototype.needAlphaBlending = function () {
  50971. return this._options.needAlphaBlending;
  50972. };
  50973. ShaderMaterial.prototype.needAlphaTesting = function () {
  50974. return this._options.needAlphaTesting;
  50975. };
  50976. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50977. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50978. this._options.uniforms.push(uniformName);
  50979. }
  50980. };
  50981. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50982. if (this._options.samplers.indexOf(name) === -1) {
  50983. this._options.samplers.push(name);
  50984. }
  50985. this._textures[name] = texture;
  50986. return this;
  50987. };
  50988. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50989. if (this._options.samplers.indexOf(name) === -1) {
  50990. this._options.samplers.push(name);
  50991. }
  50992. this._checkUniform(name);
  50993. this._textureArrays[name] = textures;
  50994. return this;
  50995. };
  50996. ShaderMaterial.prototype.setFloat = function (name, value) {
  50997. this._checkUniform(name);
  50998. this._floats[name] = value;
  50999. return this;
  51000. };
  51001. ShaderMaterial.prototype.setInt = function (name, value) {
  51002. this._checkUniform(name);
  51003. this._ints[name] = value;
  51004. return this;
  51005. };
  51006. ShaderMaterial.prototype.setFloats = function (name, value) {
  51007. this._checkUniform(name);
  51008. this._floatsArrays[name] = value;
  51009. return this;
  51010. };
  51011. ShaderMaterial.prototype.setColor3 = function (name, value) {
  51012. this._checkUniform(name);
  51013. this._colors3[name] = value;
  51014. return this;
  51015. };
  51016. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  51017. this._checkUniform(name);
  51018. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  51019. color.toArray(arr, arr.length);
  51020. return arr;
  51021. }, []);
  51022. return this;
  51023. };
  51024. ShaderMaterial.prototype.setColor4 = function (name, value) {
  51025. this._checkUniform(name);
  51026. this._colors4[name] = value;
  51027. return this;
  51028. };
  51029. ShaderMaterial.prototype.setVector2 = function (name, value) {
  51030. this._checkUniform(name);
  51031. this._vectors2[name] = value;
  51032. return this;
  51033. };
  51034. ShaderMaterial.prototype.setVector3 = function (name, value) {
  51035. this._checkUniform(name);
  51036. this._vectors3[name] = value;
  51037. return this;
  51038. };
  51039. ShaderMaterial.prototype.setVector4 = function (name, value) {
  51040. this._checkUniform(name);
  51041. this._vectors4[name] = value;
  51042. return this;
  51043. };
  51044. ShaderMaterial.prototype.setMatrix = function (name, value) {
  51045. this._checkUniform(name);
  51046. this._matrices[name] = value;
  51047. return this;
  51048. };
  51049. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  51050. this._checkUniform(name);
  51051. this._matrices3x3[name] = value;
  51052. return this;
  51053. };
  51054. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  51055. this._checkUniform(name);
  51056. this._matrices2x2[name] = value;
  51057. return this;
  51058. };
  51059. ShaderMaterial.prototype.setArray2 = function (name, value) {
  51060. this._checkUniform(name);
  51061. this._vectors2Arrays[name] = value;
  51062. return this;
  51063. };
  51064. ShaderMaterial.prototype.setArray3 = function (name, value) {
  51065. this._checkUniform(name);
  51066. this._vectors3Arrays[name] = value;
  51067. return this;
  51068. };
  51069. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51070. if (!mesh) {
  51071. return true;
  51072. }
  51073. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  51074. return false;
  51075. }
  51076. return false;
  51077. };
  51078. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  51079. var scene = this.getScene();
  51080. var engine = scene.getEngine();
  51081. if (!this.checkReadyOnEveryCall) {
  51082. if (this._renderId === scene.getRenderId()) {
  51083. if (this._checkCache(scene, mesh, useInstances)) {
  51084. return true;
  51085. }
  51086. }
  51087. }
  51088. // Instances
  51089. var defines = [];
  51090. var attribs = [];
  51091. var fallbacks = new BABYLON.EffectFallbacks();
  51092. if (useInstances) {
  51093. defines.push("#define INSTANCES");
  51094. }
  51095. for (var index = 0; index < this._options.defines.length; index++) {
  51096. defines.push(this._options.defines[index]);
  51097. }
  51098. for (var index = 0; index < this._options.attributes.length; index++) {
  51099. attribs.push(this._options.attributes[index]);
  51100. }
  51101. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51102. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51103. defines.push("#define VERTEXCOLOR");
  51104. }
  51105. // Bones
  51106. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  51107. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51108. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51109. if (mesh.numBoneInfluencers > 4) {
  51110. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51111. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51112. }
  51113. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51114. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51115. fallbacks.addCPUSkinningFallback(0, mesh);
  51116. if (this._options.uniforms.indexOf("mBones") === -1) {
  51117. this._options.uniforms.push("mBones");
  51118. }
  51119. }
  51120. else {
  51121. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51122. }
  51123. // Textures
  51124. for (var name in this._textures) {
  51125. if (!this._textures[name].isReady()) {
  51126. return false;
  51127. }
  51128. }
  51129. // Alpha test
  51130. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  51131. defines.push("#define ALPHATEST");
  51132. }
  51133. var previousEffect = this._effect;
  51134. var join = defines.join("\n");
  51135. this._effect = engine.createEffect(this._shaderPath, {
  51136. attributes: attribs,
  51137. uniformsNames: this._options.uniforms,
  51138. uniformBuffersNames: this._options.uniformBuffers,
  51139. samplers: this._options.samplers,
  51140. defines: join,
  51141. fallbacks: fallbacks,
  51142. onCompiled: this.onCompiled,
  51143. onError: this.onError
  51144. }, engine);
  51145. if (!this._effect.isReady()) {
  51146. return false;
  51147. }
  51148. if (previousEffect !== this._effect) {
  51149. scene.resetCachedMaterial();
  51150. }
  51151. this._renderId = scene.getRenderId();
  51152. return true;
  51153. };
  51154. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51155. var scene = this.getScene();
  51156. if (!this._effect) {
  51157. return;
  51158. }
  51159. if (this._options.uniforms.indexOf("world") !== -1) {
  51160. this._effect.setMatrix("world", world);
  51161. }
  51162. if (this._options.uniforms.indexOf("worldView") !== -1) {
  51163. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  51164. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  51165. }
  51166. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  51167. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  51168. }
  51169. };
  51170. ShaderMaterial.prototype.bind = function (world, mesh) {
  51171. // Std values
  51172. this.bindOnlyWorldMatrix(world);
  51173. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  51174. if (this._options.uniforms.indexOf("view") !== -1) {
  51175. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  51176. }
  51177. if (this._options.uniforms.indexOf("projection") !== -1) {
  51178. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  51179. }
  51180. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  51181. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  51182. }
  51183. // Bones
  51184. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51185. var name;
  51186. // Texture
  51187. for (name in this._textures) {
  51188. this._effect.setTexture(name, this._textures[name]);
  51189. }
  51190. // Texture arrays
  51191. for (name in this._textureArrays) {
  51192. this._effect.setTextureArray(name, this._textureArrays[name]);
  51193. }
  51194. // Int
  51195. for (name in this._ints) {
  51196. this._effect.setInt(name, this._ints[name]);
  51197. }
  51198. // Float
  51199. for (name in this._floats) {
  51200. this._effect.setFloat(name, this._floats[name]);
  51201. }
  51202. // Floats
  51203. for (name in this._floatsArrays) {
  51204. this._effect.setArray(name, this._floatsArrays[name]);
  51205. }
  51206. // Color3
  51207. for (name in this._colors3) {
  51208. this._effect.setColor3(name, this._colors3[name]);
  51209. }
  51210. for (name in this._colors3Arrays) {
  51211. this._effect.setArray3(name, this._colors3Arrays[name]);
  51212. }
  51213. // Color4
  51214. for (name in this._colors4) {
  51215. var color = this._colors4[name];
  51216. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  51217. }
  51218. // Vector2
  51219. for (name in this._vectors2) {
  51220. this._effect.setVector2(name, this._vectors2[name]);
  51221. }
  51222. // Vector3
  51223. for (name in this._vectors3) {
  51224. this._effect.setVector3(name, this._vectors3[name]);
  51225. }
  51226. // Vector4
  51227. for (name in this._vectors4) {
  51228. this._effect.setVector4(name, this._vectors4[name]);
  51229. }
  51230. // Matrix
  51231. for (name in this._matrices) {
  51232. this._effect.setMatrix(name, this._matrices[name]);
  51233. }
  51234. // Matrix 3x3
  51235. for (name in this._matrices3x3) {
  51236. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  51237. }
  51238. // Matrix 2x2
  51239. for (name in this._matrices2x2) {
  51240. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  51241. }
  51242. // Vector2Array
  51243. for (name in this._vectors2Arrays) {
  51244. this._effect.setArray2(name, this._vectors2Arrays[name]);
  51245. }
  51246. // Vector3Array
  51247. for (name in this._vectors3Arrays) {
  51248. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51249. }
  51250. }
  51251. this._afterBind(mesh);
  51252. };
  51253. ShaderMaterial.prototype.getActiveTextures = function () {
  51254. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51255. for (var name in this._textures) {
  51256. activeTextures.push(this._textures[name]);
  51257. }
  51258. for (var name in this._textureArrays) {
  51259. var array = this._textureArrays[name];
  51260. for (var index = 0; index < array.length; index++) {
  51261. activeTextures.push(array[index]);
  51262. }
  51263. }
  51264. return activeTextures;
  51265. };
  51266. ShaderMaterial.prototype.hasTexture = function (texture) {
  51267. if (_super.prototype.hasTexture.call(this, texture)) {
  51268. return true;
  51269. }
  51270. for (var name in this._textures) {
  51271. if (this._textures[name] === texture) {
  51272. return true;
  51273. }
  51274. }
  51275. for (var name in this._textureArrays) {
  51276. var array = this._textureArrays[name];
  51277. for (var index = 0; index < array.length; index++) {
  51278. if (array[index] === texture) {
  51279. return true;
  51280. }
  51281. }
  51282. }
  51283. return false;
  51284. };
  51285. ShaderMaterial.prototype.clone = function (name) {
  51286. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51287. return newShaderMaterial;
  51288. };
  51289. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51290. if (forceDisposeTextures) {
  51291. var name;
  51292. for (name in this._textures) {
  51293. this._textures[name].dispose();
  51294. }
  51295. for (name in this._textureArrays) {
  51296. var array = this._textureArrays[name];
  51297. for (var index = 0; index < array.length; index++) {
  51298. array[index].dispose();
  51299. }
  51300. }
  51301. }
  51302. this._textures = {};
  51303. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51304. };
  51305. ShaderMaterial.prototype.serialize = function () {
  51306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51307. serializationObject.customType = "BABYLON.ShaderMaterial";
  51308. serializationObject.options = this._options;
  51309. serializationObject.shaderPath = this._shaderPath;
  51310. var name;
  51311. // Texture
  51312. serializationObject.textures = {};
  51313. for (name in this._textures) {
  51314. serializationObject.textures[name] = this._textures[name].serialize();
  51315. }
  51316. // Texture arrays
  51317. serializationObject.textureArrays = {};
  51318. for (name in this._textureArrays) {
  51319. serializationObject.textureArrays[name] = [];
  51320. var array = this._textureArrays[name];
  51321. for (var index = 0; index < array.length; index++) {
  51322. serializationObject.textureArrays[name].push(array[index].serialize());
  51323. }
  51324. }
  51325. // Float
  51326. serializationObject.floats = {};
  51327. for (name in this._floats) {
  51328. serializationObject.floats[name] = this._floats[name];
  51329. }
  51330. // Float s
  51331. serializationObject.FloatArrays = {};
  51332. for (name in this._floatsArrays) {
  51333. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51334. }
  51335. // Color3
  51336. serializationObject.colors3 = {};
  51337. for (name in this._colors3) {
  51338. serializationObject.colors3[name] = this._colors3[name].asArray();
  51339. }
  51340. // Color3 array
  51341. serializationObject.colors3Arrays = {};
  51342. for (name in this._colors3Arrays) {
  51343. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51344. }
  51345. // Color4
  51346. serializationObject.colors4 = {};
  51347. for (name in this._colors4) {
  51348. serializationObject.colors4[name] = this._colors4[name].asArray();
  51349. }
  51350. // Vector2
  51351. serializationObject.vectors2 = {};
  51352. for (name in this._vectors2) {
  51353. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51354. }
  51355. // Vector3
  51356. serializationObject.vectors3 = {};
  51357. for (name in this._vectors3) {
  51358. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51359. }
  51360. // Vector4
  51361. serializationObject.vectors4 = {};
  51362. for (name in this._vectors4) {
  51363. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51364. }
  51365. // Matrix
  51366. serializationObject.matrices = {};
  51367. for (name in this._matrices) {
  51368. serializationObject.matrices[name] = this._matrices[name].asArray();
  51369. }
  51370. // Matrix 3x3
  51371. serializationObject.matrices3x3 = {};
  51372. for (name in this._matrices3x3) {
  51373. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51374. }
  51375. // Matrix 2x2
  51376. serializationObject.matrices2x2 = {};
  51377. for (name in this._matrices2x2) {
  51378. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51379. }
  51380. // Vector2Array
  51381. serializationObject.vectors2Arrays = {};
  51382. for (name in this._vectors2Arrays) {
  51383. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51384. }
  51385. // Vector3Array
  51386. serializationObject.vectors3Arrays = {};
  51387. for (name in this._vectors3Arrays) {
  51388. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51389. }
  51390. return serializationObject;
  51391. };
  51392. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51393. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51394. var name;
  51395. // Texture
  51396. for (name in source.textures) {
  51397. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51398. }
  51399. // Texture arrays
  51400. for (name in source.textureArrays) {
  51401. var array = source.textureArrays[name];
  51402. var textureArray = new Array();
  51403. for (var index = 0; index < array.length; index++) {
  51404. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51405. }
  51406. material.setTextureArray(name, textureArray);
  51407. }
  51408. // Float
  51409. for (name in source.floats) {
  51410. material.setFloat(name, source.floats[name]);
  51411. }
  51412. // Float s
  51413. for (name in source.floatsArrays) {
  51414. material.setFloats(name, source.floatsArrays[name]);
  51415. }
  51416. // Color3
  51417. for (name in source.colors3) {
  51418. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51419. }
  51420. // Color3 arrays
  51421. for (name in source.colors3Arrays) {
  51422. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51423. if (i % 3 === 0) {
  51424. arr.push([num]);
  51425. }
  51426. else {
  51427. arr[arr.length - 1].push(num);
  51428. }
  51429. return arr;
  51430. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51431. material.setColor3Array(name, colors);
  51432. }
  51433. // Color4
  51434. for (name in source.colors4) {
  51435. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51436. }
  51437. // Vector2
  51438. for (name in source.vectors2) {
  51439. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51440. }
  51441. // Vector3
  51442. for (name in source.vectors3) {
  51443. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51444. }
  51445. // Vector4
  51446. for (name in source.vectors4) {
  51447. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51448. }
  51449. // Matrix
  51450. for (name in source.matrices) {
  51451. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51452. }
  51453. // Matrix 3x3
  51454. for (name in source.matrices3x3) {
  51455. material.setMatrix3x3(name, source.matrices3x3[name]);
  51456. }
  51457. // Matrix 2x2
  51458. for (name in source.matrices2x2) {
  51459. material.setMatrix2x2(name, source.matrices2x2[name]);
  51460. }
  51461. // Vector2Array
  51462. for (name in source.vectors2Arrays) {
  51463. material.setArray2(name, source.vectors2Arrays[name]);
  51464. }
  51465. // Vector3Array
  51466. for (name in source.vectors3Arrays) {
  51467. material.setArray3(name, source.vectors3Arrays[name]);
  51468. }
  51469. return material;
  51470. };
  51471. return ShaderMaterial;
  51472. }(BABYLON.Material));
  51473. BABYLON.ShaderMaterial = ShaderMaterial;
  51474. })(BABYLON || (BABYLON = {}));
  51475. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51476. var BABYLON;
  51477. (function (BABYLON) {
  51478. var GroundMesh = /** @class */ (function (_super) {
  51479. __extends(GroundMesh, _super);
  51480. function GroundMesh(name, scene) {
  51481. var _this = _super.call(this, name, scene) || this;
  51482. _this.generateOctree = false;
  51483. return _this;
  51484. }
  51485. GroundMesh.prototype.getClassName = function () {
  51486. return "GroundMesh";
  51487. };
  51488. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51489. get: function () {
  51490. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51496. get: function () {
  51497. return this._subdivisionsX;
  51498. },
  51499. enumerable: true,
  51500. configurable: true
  51501. });
  51502. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51503. get: function () {
  51504. return this._subdivisionsY;
  51505. },
  51506. enumerable: true,
  51507. configurable: true
  51508. });
  51509. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51510. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51511. this._subdivisionsX = chunksCount;
  51512. this._subdivisionsY = chunksCount;
  51513. this.subdivide(chunksCount);
  51514. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51515. };
  51516. /**
  51517. * Returns a height (y) value in the Worl system :
  51518. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51519. * Returns the ground y position if (x, z) are outside the ground surface.
  51520. */
  51521. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51522. var world = this.getWorldMatrix();
  51523. var invMat = BABYLON.Tmp.Matrix[5];
  51524. world.invertToRef(invMat);
  51525. var tmpVect = BABYLON.Tmp.Vector3[8];
  51526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51527. x = tmpVect.x;
  51528. z = tmpVect.z;
  51529. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51530. return this.position.y;
  51531. }
  51532. if (!this._heightQuads || this._heightQuads.length == 0) {
  51533. this._initHeightQuads();
  51534. this._computeHeightQuads();
  51535. }
  51536. var facet = this._getFacetAt(x, z);
  51537. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51538. // return y in the World system
  51539. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51540. return tmpVect.y;
  51541. };
  51542. /**
  51543. * Returns a normalized vector (Vector3) orthogonal to the ground
  51544. * at the ground coordinates (x, z) expressed in the World system.
  51545. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51546. */
  51547. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51548. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51549. this.getNormalAtCoordinatesToRef(x, z, normal);
  51550. return normal;
  51551. };
  51552. /**
  51553. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51554. * at the ground coordinates (x, z) expressed in the World system.
  51555. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51556. * Returns the GroundMesh.
  51557. */
  51558. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51559. var world = this.getWorldMatrix();
  51560. var tmpMat = BABYLON.Tmp.Matrix[5];
  51561. world.invertToRef(tmpMat);
  51562. var tmpVect = BABYLON.Tmp.Vector3[8];
  51563. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51564. x = tmpVect.x;
  51565. z = tmpVect.z;
  51566. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51567. return this;
  51568. }
  51569. if (!this._heightQuads || this._heightQuads.length == 0) {
  51570. this._initHeightQuads();
  51571. this._computeHeightQuads();
  51572. }
  51573. var facet = this._getFacetAt(x, z);
  51574. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51575. return this;
  51576. };
  51577. /**
  51578. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51579. * if the ground has been updated.
  51580. * This can be used in the render loop.
  51581. * Returns the GroundMesh.
  51582. */
  51583. GroundMesh.prototype.updateCoordinateHeights = function () {
  51584. if (!this._heightQuads || this._heightQuads.length == 0) {
  51585. this._initHeightQuads();
  51586. }
  51587. this._computeHeightQuads();
  51588. return this;
  51589. };
  51590. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51591. GroundMesh.prototype._getFacetAt = function (x, z) {
  51592. // retrieve col and row from x, z coordinates in the ground local system
  51593. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51594. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51595. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51596. var facet;
  51597. if (z < quad.slope.x * x + quad.slope.y) {
  51598. facet = quad.facet1;
  51599. }
  51600. else {
  51601. facet = quad.facet2;
  51602. }
  51603. return facet;
  51604. };
  51605. // Creates and populates the heightMap array with "facet" elements :
  51606. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51607. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51608. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51609. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51610. // Returns the GroundMesh.
  51611. GroundMesh.prototype._initHeightQuads = function () {
  51612. var subdivisionsX = this._subdivisionsX;
  51613. var subdivisionsY = this._subdivisionsY;
  51614. this._heightQuads = new Array();
  51615. for (var row = 0; row < subdivisionsY; row++) {
  51616. for (var col = 0; col < subdivisionsX; col++) {
  51617. 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) };
  51618. this._heightQuads[row * subdivisionsX + col] = quad;
  51619. }
  51620. }
  51621. return this;
  51622. };
  51623. // Compute each quad element values and update the the heightMap array :
  51624. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51625. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51626. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51627. // Returns the GroundMesh.
  51628. GroundMesh.prototype._computeHeightQuads = function () {
  51629. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51630. if (!positions) {
  51631. return this;
  51632. }
  51633. var v1 = BABYLON.Tmp.Vector3[3];
  51634. var v2 = BABYLON.Tmp.Vector3[2];
  51635. var v3 = BABYLON.Tmp.Vector3[1];
  51636. var v4 = BABYLON.Tmp.Vector3[0];
  51637. var v1v2 = BABYLON.Tmp.Vector3[4];
  51638. var v1v3 = BABYLON.Tmp.Vector3[5];
  51639. var v1v4 = BABYLON.Tmp.Vector3[6];
  51640. var norm1 = BABYLON.Tmp.Vector3[7];
  51641. var norm2 = BABYLON.Tmp.Vector3[8];
  51642. var i = 0;
  51643. var j = 0;
  51644. var k = 0;
  51645. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51646. var h = 0;
  51647. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51648. var d2 = 0;
  51649. var subdivisionsX = this._subdivisionsX;
  51650. var subdivisionsY = this._subdivisionsY;
  51651. for (var row = 0; row < subdivisionsY; row++) {
  51652. for (var col = 0; col < subdivisionsX; col++) {
  51653. i = col * 3;
  51654. j = row * (subdivisionsX + 1) * 3;
  51655. k = (row + 1) * (subdivisionsX + 1) * 3;
  51656. v1.x = positions[j + i];
  51657. v1.y = positions[j + i + 1];
  51658. v1.z = positions[j + i + 2];
  51659. v2.x = positions[j + i + 3];
  51660. v2.y = positions[j + i + 4];
  51661. v2.z = positions[j + i + 5];
  51662. v3.x = positions[k + i];
  51663. v3.y = positions[k + i + 1];
  51664. v3.z = positions[k + i + 2];
  51665. v4.x = positions[k + i + 3];
  51666. v4.y = positions[k + i + 4];
  51667. v4.z = positions[k + i + 5];
  51668. // 2D slope V1V4
  51669. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51670. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51671. // facet equations :
  51672. // we compute each facet normal vector
  51673. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51674. // we compute the value d by applying the equation to v1 which belongs to the plane
  51675. // then we store the facet equation in a Vector4
  51676. v2.subtractToRef(v1, v1v2);
  51677. v3.subtractToRef(v1, v1v3);
  51678. v4.subtractToRef(v1, v1v4);
  51679. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51680. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51681. norm1.normalize();
  51682. norm2.normalize();
  51683. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51684. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51685. var quad = this._heightQuads[row * subdivisionsX + col];
  51686. quad.slope.copyFromFloats(cd, h);
  51687. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51688. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51689. }
  51690. }
  51691. return this;
  51692. };
  51693. GroundMesh.prototype.serialize = function (serializationObject) {
  51694. _super.prototype.serialize.call(this, serializationObject);
  51695. serializationObject.subdivisionsX = this._subdivisionsX;
  51696. serializationObject.subdivisionsY = this._subdivisionsY;
  51697. serializationObject.minX = this._minX;
  51698. serializationObject.maxX = this._maxX;
  51699. serializationObject.minZ = this._minZ;
  51700. serializationObject.maxZ = this._maxZ;
  51701. serializationObject.width = this._width;
  51702. serializationObject.height = this._height;
  51703. };
  51704. GroundMesh.Parse = function (parsedMesh, scene) {
  51705. var result = new GroundMesh(parsedMesh.name, scene);
  51706. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51707. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51708. result._minX = parsedMesh.minX;
  51709. result._maxX = parsedMesh.maxX;
  51710. result._minZ = parsedMesh.minZ;
  51711. result._maxZ = parsedMesh.maxZ;
  51712. result._width = parsedMesh.width;
  51713. result._height = parsedMesh.height;
  51714. return result;
  51715. };
  51716. return GroundMesh;
  51717. }(BABYLON.Mesh));
  51718. BABYLON.GroundMesh = GroundMesh;
  51719. })(BABYLON || (BABYLON = {}));
  51720. //# sourceMappingURL=babylon.groundMesh.js.map
  51721. var BABYLON;
  51722. (function (BABYLON) {
  51723. /**
  51724. * Creates an instance based on a source mesh.
  51725. */
  51726. var InstancedMesh = /** @class */ (function (_super) {
  51727. __extends(InstancedMesh, _super);
  51728. function InstancedMesh(name, source) {
  51729. var _this = _super.call(this, name, source.getScene()) || this;
  51730. source.instances.push(_this);
  51731. _this._sourceMesh = source;
  51732. _this.position.copyFrom(source.position);
  51733. _this.rotation.copyFrom(source.rotation);
  51734. _this.scaling.copyFrom(source.scaling);
  51735. if (source.rotationQuaternion) {
  51736. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51737. }
  51738. _this.infiniteDistance = source.infiniteDistance;
  51739. _this.setPivotMatrix(source.getPivotMatrix());
  51740. _this.refreshBoundingInfo();
  51741. _this._syncSubMeshes();
  51742. return _this;
  51743. }
  51744. /**
  51745. * Returns the string "InstancedMesh".
  51746. */
  51747. InstancedMesh.prototype.getClassName = function () {
  51748. return "InstancedMesh";
  51749. };
  51750. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51751. // Methods
  51752. get: function () {
  51753. return this._sourceMesh.receiveShadows;
  51754. },
  51755. enumerable: true,
  51756. configurable: true
  51757. });
  51758. Object.defineProperty(InstancedMesh.prototype, "material", {
  51759. get: function () {
  51760. return this._sourceMesh.material;
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51766. get: function () {
  51767. return this._sourceMesh.visibility;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51773. get: function () {
  51774. return this._sourceMesh.skeleton;
  51775. },
  51776. enumerable: true,
  51777. configurable: true
  51778. });
  51779. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51780. get: function () {
  51781. return this._sourceMesh.renderingGroupId;
  51782. },
  51783. enumerable: true,
  51784. configurable: true
  51785. });
  51786. /**
  51787. * Returns the total number of vertices (integer).
  51788. */
  51789. InstancedMesh.prototype.getTotalVertices = function () {
  51790. return this._sourceMesh.getTotalVertices();
  51791. };
  51792. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51793. get: function () {
  51794. return this._sourceMesh;
  51795. },
  51796. enumerable: true,
  51797. configurable: true
  51798. });
  51799. /**
  51800. * Is this node ready to be used/rendered
  51801. * @return {boolean} is it ready
  51802. */
  51803. InstancedMesh.prototype.isReady = function () {
  51804. return this._sourceMesh.isReady(true);
  51805. };
  51806. /**
  51807. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51808. */
  51809. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51810. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51811. };
  51812. /**
  51813. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51814. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51815. * The `data` are either a numeric array either a Float32Array.
  51816. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51817. * 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).
  51818. * Note that a new underlying VertexBuffer object is created each call.
  51819. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51820. *
  51821. * Possible `kind` values :
  51822. * - BABYLON.VertexBuffer.PositionKind
  51823. * - BABYLON.VertexBuffer.UVKind
  51824. * - BABYLON.VertexBuffer.UV2Kind
  51825. * - BABYLON.VertexBuffer.UV3Kind
  51826. * - BABYLON.VertexBuffer.UV4Kind
  51827. * - BABYLON.VertexBuffer.UV5Kind
  51828. * - BABYLON.VertexBuffer.UV6Kind
  51829. * - BABYLON.VertexBuffer.ColorKind
  51830. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51831. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51832. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51833. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51834. *
  51835. * Returns the Mesh.
  51836. */
  51837. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51838. if (this.sourceMesh) {
  51839. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51840. }
  51841. return this.sourceMesh;
  51842. };
  51843. /**
  51844. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51845. * If the mesh has no geometry, it is simply returned as it is.
  51846. * The `data` are either a numeric array either a Float32Array.
  51847. * No new underlying VertexBuffer object is created.
  51848. * 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.
  51849. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51850. *
  51851. * Possible `kind` values :
  51852. * - BABYLON.VertexBuffer.PositionKind
  51853. * - BABYLON.VertexBuffer.UVKind
  51854. * - BABYLON.VertexBuffer.UV2Kind
  51855. * - BABYLON.VertexBuffer.UV3Kind
  51856. * - BABYLON.VertexBuffer.UV4Kind
  51857. * - BABYLON.VertexBuffer.UV5Kind
  51858. * - BABYLON.VertexBuffer.UV6Kind
  51859. * - BABYLON.VertexBuffer.ColorKind
  51860. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51861. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51862. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51863. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51864. *
  51865. * Returns the Mesh.
  51866. */
  51867. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51868. if (this.sourceMesh) {
  51869. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51870. }
  51871. return this.sourceMesh;
  51872. };
  51873. /**
  51874. * Sets the mesh indices.
  51875. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51876. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51877. * This method creates a new index buffer each call.
  51878. * Returns the Mesh.
  51879. */
  51880. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51881. if (totalVertices === void 0) { totalVertices = null; }
  51882. if (this.sourceMesh) {
  51883. this.sourceMesh.setIndices(indices, totalVertices);
  51884. }
  51885. return this.sourceMesh;
  51886. };
  51887. /**
  51888. * Boolean : True if the mesh owns the requested kind of data.
  51889. */
  51890. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51891. return this._sourceMesh.isVerticesDataPresent(kind);
  51892. };
  51893. /**
  51894. * Returns an array of indices (IndicesArray).
  51895. */
  51896. InstancedMesh.prototype.getIndices = function () {
  51897. return this._sourceMesh.getIndices();
  51898. };
  51899. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51900. get: function () {
  51901. return this._sourceMesh._positions;
  51902. },
  51903. enumerable: true,
  51904. configurable: true
  51905. });
  51906. /**
  51907. * Sets a new updated BoundingInfo to the mesh.
  51908. * Returns the mesh.
  51909. */
  51910. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51911. var meshBB = this._sourceMesh.getBoundingInfo();
  51912. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51913. this._updateBoundingInfo();
  51914. return this;
  51915. };
  51916. InstancedMesh.prototype._preActivate = function () {
  51917. if (this._currentLOD) {
  51918. this._currentLOD._preActivate();
  51919. }
  51920. return this;
  51921. };
  51922. InstancedMesh.prototype._activate = function (renderId) {
  51923. if (this._currentLOD) {
  51924. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51925. }
  51926. return this;
  51927. };
  51928. /**
  51929. * Returns the current associated LOD AbstractMesh.
  51930. */
  51931. InstancedMesh.prototype.getLOD = function (camera) {
  51932. if (!camera) {
  51933. return this;
  51934. }
  51935. var boundingInfo = this.getBoundingInfo();
  51936. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51937. if (this._currentLOD === this.sourceMesh) {
  51938. return this;
  51939. }
  51940. return this._currentLOD;
  51941. };
  51942. InstancedMesh.prototype._syncSubMeshes = function () {
  51943. this.releaseSubMeshes();
  51944. if (this._sourceMesh.subMeshes) {
  51945. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51946. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51947. }
  51948. }
  51949. return this;
  51950. };
  51951. InstancedMesh.prototype._generatePointsArray = function () {
  51952. return this._sourceMesh._generatePointsArray();
  51953. };
  51954. /**
  51955. * Creates a new InstancedMesh from the current mesh.
  51956. * - name (string) : the cloned mesh name
  51957. * - newParent (optional Node) : the optional Node to parent the clone to.
  51958. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51959. *
  51960. * Returns the clone.
  51961. */
  51962. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51963. var result = this._sourceMesh.createInstance(name);
  51964. // Deep copy
  51965. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51966. // Bounding info
  51967. this.refreshBoundingInfo();
  51968. // Parent
  51969. if (newParent) {
  51970. result.parent = newParent;
  51971. }
  51972. if (!doNotCloneChildren) {
  51973. // Children
  51974. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51975. var mesh = this.getScene().meshes[index];
  51976. if (mesh.parent === this) {
  51977. mesh.clone(mesh.name, result);
  51978. }
  51979. }
  51980. }
  51981. result.computeWorldMatrix(true);
  51982. return result;
  51983. };
  51984. /**
  51985. * Disposes the InstancedMesh.
  51986. * Returns nothing.
  51987. */
  51988. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51989. // Remove from mesh
  51990. var index = this._sourceMesh.instances.indexOf(this);
  51991. this._sourceMesh.instances.splice(index, 1);
  51992. _super.prototype.dispose.call(this, doNotRecurse);
  51993. };
  51994. return InstancedMesh;
  51995. }(BABYLON.AbstractMesh));
  51996. BABYLON.InstancedMesh = InstancedMesh;
  51997. })(BABYLON || (BABYLON = {}));
  51998. //# sourceMappingURL=babylon.instancedMesh.js.map
  51999. var BABYLON;
  52000. (function (BABYLON) {
  52001. var LinesMesh = /** @class */ (function (_super) {
  52002. __extends(LinesMesh, _super);
  52003. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  52004. if (scene === void 0) { scene = null; }
  52005. if (parent === void 0) { parent = null; }
  52006. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  52007. _this.useVertexColor = useVertexColor;
  52008. _this.useVertexAlpha = useVertexAlpha;
  52009. _this.color = new BABYLON.Color3(1, 1, 1);
  52010. _this.alpha = 1;
  52011. if (source) {
  52012. _this.color = source.color.clone();
  52013. _this.alpha = source.alpha;
  52014. _this.useVertexColor = source.useVertexColor;
  52015. _this.useVertexAlpha = source.useVertexAlpha;
  52016. }
  52017. _this._intersectionThreshold = 0.1;
  52018. var defines = [];
  52019. var options = {
  52020. attributes: [BABYLON.VertexBuffer.PositionKind],
  52021. uniforms: ["world", "viewProjection"],
  52022. needAlphaBlending: true,
  52023. defines: defines
  52024. };
  52025. if (useVertexAlpha === false) {
  52026. options.needAlphaBlending = false;
  52027. }
  52028. if (!useVertexColor) {
  52029. options.uniforms.push("color");
  52030. }
  52031. else {
  52032. options.defines.push("#define VERTEXCOLOR");
  52033. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  52034. }
  52035. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  52036. return _this;
  52037. }
  52038. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  52039. /**
  52040. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52041. * This margin is expressed in world space coordinates, so its value may vary.
  52042. * Default value is 0.1
  52043. * @returns the intersection Threshold value.
  52044. */
  52045. get: function () {
  52046. return this._intersectionThreshold;
  52047. },
  52048. /**
  52049. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52050. * This margin is expressed in world space coordinates, so its value may vary.
  52051. * @param value the new threshold to apply
  52052. */
  52053. set: function (value) {
  52054. if (this._intersectionThreshold === value) {
  52055. return;
  52056. }
  52057. this._intersectionThreshold = value;
  52058. if (this.geometry) {
  52059. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  52060. }
  52061. },
  52062. enumerable: true,
  52063. configurable: true
  52064. });
  52065. /**
  52066. * Returns the string "LineMesh"
  52067. */
  52068. LinesMesh.prototype.getClassName = function () {
  52069. return "LinesMesh";
  52070. };
  52071. Object.defineProperty(LinesMesh.prototype, "material", {
  52072. get: function () {
  52073. return this._colorShader;
  52074. },
  52075. set: function (value) {
  52076. // Do nothing
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  52082. get: function () {
  52083. return false;
  52084. },
  52085. enumerable: true,
  52086. configurable: true
  52087. });
  52088. LinesMesh.prototype.createInstance = function (name) {
  52089. throw new Error("LinesMeshes do not support createInstance.");
  52090. };
  52091. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  52092. if (!this._geometry) {
  52093. return this;
  52094. }
  52095. // VBOs
  52096. this._geometry._bind(this._colorShader.getEffect());
  52097. // Color
  52098. if (!this.useVertexColor) {
  52099. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  52100. }
  52101. return this;
  52102. };
  52103. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  52104. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  52105. return this;
  52106. }
  52107. var engine = this.getScene().getEngine();
  52108. // Draw order
  52109. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  52110. return this;
  52111. };
  52112. LinesMesh.prototype.dispose = function (doNotRecurse) {
  52113. this._colorShader.dispose();
  52114. _super.prototype.dispose.call(this, doNotRecurse);
  52115. };
  52116. /**
  52117. * Returns a new LineMesh object cloned from the current one.
  52118. */
  52119. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  52120. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  52121. };
  52122. return LinesMesh;
  52123. }(BABYLON.Mesh));
  52124. BABYLON.LinesMesh = LinesMesh;
  52125. })(BABYLON || (BABYLON = {}));
  52126. //# sourceMappingURL=babylon.linesMesh.js.map
  52127. var BABYLON;
  52128. (function (BABYLON) {
  52129. var MeshBuilder = /** @class */ (function () {
  52130. function MeshBuilder() {
  52131. }
  52132. MeshBuilder.updateSideOrientation = function (orientation) {
  52133. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  52134. return BABYLON.Mesh.DOUBLESIDE;
  52135. }
  52136. if (orientation === undefined || orientation === null) {
  52137. return BABYLON.Mesh.FRONTSIDE;
  52138. }
  52139. return orientation;
  52140. };
  52141. /**
  52142. * Creates a box mesh.
  52143. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  52144. * The parameter `size` sets the size (float) of each box side (default 1).
  52145. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  52146. * 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).
  52147. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52149. * 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).
  52150. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52152. */
  52153. MeshBuilder.CreateBox = function (name, options, scene) {
  52154. if (scene === void 0) { scene = null; }
  52155. var box = new BABYLON.Mesh(name, scene);
  52156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52157. box._originalBuilderSideOrientation = options.sideOrientation;
  52158. var vertexData = BABYLON.VertexData.CreateBox(options);
  52159. vertexData.applyToMesh(box, options.updatable);
  52160. return box;
  52161. };
  52162. /**
  52163. * Creates a sphere mesh.
  52164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  52165. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  52166. * 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`).
  52167. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  52168. * 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
  52169. * 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).
  52170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52171. * 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).
  52172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52174. */
  52175. MeshBuilder.CreateSphere = function (name, options, scene) {
  52176. var sphere = new BABYLON.Mesh(name, scene);
  52177. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52178. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52179. var vertexData = BABYLON.VertexData.CreateSphere(options);
  52180. vertexData.applyToMesh(sphere, options.updatable);
  52181. return sphere;
  52182. };
  52183. /**
  52184. * Creates a plane polygonal mesh. By default, this is a disc.
  52185. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  52186. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  52187. * 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.
  52188. * 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
  52189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52190. * 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).
  52191. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52193. */
  52194. MeshBuilder.CreateDisc = function (name, options, scene) {
  52195. if (scene === void 0) { scene = null; }
  52196. var disc = new BABYLON.Mesh(name, scene);
  52197. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52198. disc._originalBuilderSideOrientation = options.sideOrientation;
  52199. var vertexData = BABYLON.VertexData.CreateDisc(options);
  52200. vertexData.applyToMesh(disc, options.updatable);
  52201. return disc;
  52202. };
  52203. /**
  52204. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  52205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  52206. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  52207. * 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`).
  52208. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  52209. * 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.
  52210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52211. * 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).
  52212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52214. */
  52215. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  52216. var sphere = new BABYLON.Mesh(name, scene);
  52217. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52218. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52219. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  52220. vertexData.applyToMesh(sphere, options.updatable);
  52221. return sphere;
  52222. };
  52223. ;
  52224. /**
  52225. * Creates a ribbon mesh.
  52226. * 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.
  52227. *
  52228. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  52229. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  52230. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  52231. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  52232. * 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.
  52233. * 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.
  52234. * 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
  52235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52236. * 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).
  52237. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52238. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52239. * 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.
  52240. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  52241. * 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
  52242. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  52243. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  52244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52245. */
  52246. MeshBuilder.CreateRibbon = function (name, options, scene) {
  52247. if (scene === void 0) { scene = null; }
  52248. var pathArray = options.pathArray;
  52249. var closeArray = options.closeArray;
  52250. var closePath = options.closePath;
  52251. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52252. var instance = options.instance;
  52253. var updatable = options.updatable;
  52254. if (instance) {
  52255. // positionFunction : ribbon case
  52256. // only pathArray and sideOrientation parameters are taken into account for positions update
  52257. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52258. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52259. var positionFunction = function (positions) {
  52260. var minlg = pathArray[0].length;
  52261. var i = 0;
  52262. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52263. for (var si = 1; si <= ns; si++) {
  52264. for (var p = 0; p < pathArray.length; p++) {
  52265. var path = pathArray[p];
  52266. var l = path.length;
  52267. minlg = (minlg < l) ? minlg : l;
  52268. var j = 0;
  52269. while (j < minlg) {
  52270. positions[i] = path[j].x;
  52271. positions[i + 1] = path[j].y;
  52272. positions[i + 2] = path[j].z;
  52273. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52274. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52275. }
  52276. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52277. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52278. }
  52279. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52280. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52281. }
  52282. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52283. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52284. }
  52285. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52286. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52287. }
  52288. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52289. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52290. }
  52291. j++;
  52292. i += 3;
  52293. }
  52294. if (instance._closePath) {
  52295. positions[i] = path[0].x;
  52296. positions[i + 1] = path[0].y;
  52297. positions[i + 2] = path[0].z;
  52298. i += 3;
  52299. }
  52300. }
  52301. }
  52302. };
  52303. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52304. positionFunction(positions);
  52305. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52306. instance._boundingInfo.update(instance._worldMatrix);
  52307. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52308. if (options.colors) {
  52309. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52310. for (var c = 0; c < options.colors.length; c++) {
  52311. colors[c * 4] = options.colors[c].r;
  52312. colors[c * 4 + 1] = options.colors[c].g;
  52313. colors[c * 4 + 2] = options.colors[c].b;
  52314. colors[c * 4 + 3] = options.colors[c].a;
  52315. }
  52316. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52317. }
  52318. if (options.uvs) {
  52319. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52320. for (var i = 0; i < options.uvs.length; i++) {
  52321. uvs[i * 2] = options.uvs[i].x;
  52322. uvs[i * 2 + 1] = options.uvs[i].y;
  52323. }
  52324. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52325. }
  52326. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52327. var indices = instance.getIndices();
  52328. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52329. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52330. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52331. if (instance._closePath) {
  52332. var indexFirst = 0;
  52333. var indexLast = 0;
  52334. for (var p = 0; p < pathArray.length; p++) {
  52335. indexFirst = instance._idx[p] * 3;
  52336. if (p + 1 < pathArray.length) {
  52337. indexLast = (instance._idx[p + 1] - 1) * 3;
  52338. }
  52339. else {
  52340. indexLast = normals.length - 3;
  52341. }
  52342. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52343. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52344. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52345. normals[indexLast] = normals[indexFirst];
  52346. normals[indexLast + 1] = normals[indexFirst + 1];
  52347. normals[indexLast + 2] = normals[indexFirst + 2];
  52348. }
  52349. }
  52350. if (!(instance.areNormalsFrozen)) {
  52351. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52352. }
  52353. }
  52354. return instance;
  52355. }
  52356. else {
  52357. var ribbon = new BABYLON.Mesh(name, scene);
  52358. ribbon._originalBuilderSideOrientation = sideOrientation;
  52359. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52360. if (closePath) {
  52361. ribbon._idx = vertexData._idx;
  52362. }
  52363. ribbon._closePath = closePath;
  52364. ribbon._closeArray = closeArray;
  52365. vertexData.applyToMesh(ribbon, updatable);
  52366. return ribbon;
  52367. }
  52368. };
  52369. /**
  52370. * Creates a cylinder or a cone mesh.
  52371. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52372. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52373. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52374. * 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.
  52375. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52376. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52377. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52378. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52379. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52380. * 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).
  52381. * 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
  52382. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52383. * 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
  52384. * 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.
  52385. * If `enclose` is false, a ring surface is one element.
  52386. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52387. * 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
  52388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52389. * 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).
  52390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52392. */
  52393. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52394. var cylinder = new BABYLON.Mesh(name, scene);
  52395. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52396. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52397. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52398. vertexData.applyToMesh(cylinder, options.updatable);
  52399. return cylinder;
  52400. };
  52401. /**
  52402. * Creates a torus mesh.
  52403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52404. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52405. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52406. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52408. * 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).
  52409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52411. */
  52412. MeshBuilder.CreateTorus = function (name, options, scene) {
  52413. var torus = new BABYLON.Mesh(name, scene);
  52414. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52415. torus._originalBuilderSideOrientation = options.sideOrientation;
  52416. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52417. vertexData.applyToMesh(torus, options.updatable);
  52418. return torus;
  52419. };
  52420. /**
  52421. * Creates a torus knot mesh.
  52422. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52423. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52424. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52425. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52426. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52428. * 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).
  52429. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52431. */
  52432. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52433. var torusKnot = new BABYLON.Mesh(name, scene);
  52434. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52435. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52436. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52437. vertexData.applyToMesh(torusKnot, options.updatable);
  52438. return torusKnot;
  52439. };
  52440. /**
  52441. * Creates a line system mesh.
  52442. * A line system is a pool of many lines gathered in a single mesh.
  52443. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52444. * 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.
  52445. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52446. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52447. * 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
  52448. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52449. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52450. * 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
  52451. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52453. */
  52454. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52455. var instance = options.instance;
  52456. var lines = options.lines;
  52457. var colors = options.colors;
  52458. if (instance) {
  52459. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52460. var vertexColor;
  52461. var lineColors;
  52462. if (colors) {
  52463. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52464. }
  52465. var i = 0;
  52466. var c = 0;
  52467. for (var l = 0; l < lines.length; l++) {
  52468. var points = lines[l];
  52469. for (var p = 0; p < points.length; p++) {
  52470. positions[i] = points[p].x;
  52471. positions[i + 1] = points[p].y;
  52472. positions[i + 2] = points[p].z;
  52473. if (colors && vertexColor) {
  52474. lineColors = colors[l];
  52475. vertexColor[c] = lineColors[p].r;
  52476. vertexColor[c + 1] = lineColors[p].g;
  52477. vertexColor[c + 2] = lineColors[p].b;
  52478. vertexColor[c + 3] = lineColors[p].a;
  52479. c += 4;
  52480. }
  52481. i += 3;
  52482. }
  52483. }
  52484. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52485. if (colors && vertexColor) {
  52486. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52487. }
  52488. return instance;
  52489. }
  52490. // line system creation
  52491. var useVertexColor = (colors) ? true : false;
  52492. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52493. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52494. vertexData.applyToMesh(lineSystem, options.updatable);
  52495. return lineSystem;
  52496. };
  52497. /**
  52498. * Creates a line mesh.
  52499. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52500. * 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.
  52501. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52502. * The parameter `points` is an array successive Vector3.
  52503. * 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
  52504. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52505. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52506. * When updating an instance, remember that only point positions can change, not the number of points.
  52507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52508. */
  52509. MeshBuilder.CreateLines = function (name, options, scene) {
  52510. if (scene === void 0) { scene = null; }
  52511. var colors = (options.colors) ? [options.colors] : null;
  52512. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52513. return lines;
  52514. };
  52515. /**
  52516. * Creates a dashed line mesh.
  52517. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52518. * 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.
  52519. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52520. * The parameter `points` is an array successive Vector3.
  52521. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52522. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52523. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52524. * 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
  52525. * When updating an instance, remember that only point positions can change, not the number of points.
  52526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52527. */
  52528. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52529. if (scene === void 0) { scene = null; }
  52530. var points = options.points;
  52531. var instance = options.instance;
  52532. var gapSize = options.gapSize || 1;
  52533. var dashSize = options.dashSize || 3;
  52534. if (instance) {
  52535. var positionFunction = function (positions) {
  52536. var curvect = BABYLON.Vector3.Zero();
  52537. var nbSeg = positions.length / 6;
  52538. var lg = 0;
  52539. var nb = 0;
  52540. var shft = 0;
  52541. var dashshft = 0;
  52542. var curshft = 0;
  52543. var p = 0;
  52544. var i = 0;
  52545. var j = 0;
  52546. for (i = 0; i < points.length - 1; i++) {
  52547. points[i + 1].subtractToRef(points[i], curvect);
  52548. lg += curvect.length();
  52549. }
  52550. shft = lg / nbSeg;
  52551. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52552. for (i = 0; i < points.length - 1; i++) {
  52553. points[i + 1].subtractToRef(points[i], curvect);
  52554. nb = Math.floor(curvect.length() / shft);
  52555. curvect.normalize();
  52556. j = 0;
  52557. while (j < nb && p < positions.length) {
  52558. curshft = shft * j;
  52559. positions[p] = points[i].x + curshft * curvect.x;
  52560. positions[p + 1] = points[i].y + curshft * curvect.y;
  52561. positions[p + 2] = points[i].z + curshft * curvect.z;
  52562. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52563. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52564. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52565. p += 6;
  52566. j++;
  52567. }
  52568. }
  52569. while (p < positions.length) {
  52570. positions[p] = points[i].x;
  52571. positions[p + 1] = points[i].y;
  52572. positions[p + 2] = points[i].z;
  52573. p += 3;
  52574. }
  52575. };
  52576. instance.updateMeshPositions(positionFunction, false);
  52577. return instance;
  52578. }
  52579. // dashed lines creation
  52580. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52581. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52582. vertexData.applyToMesh(dashedLines, options.updatable);
  52583. dashedLines.dashSize = dashSize;
  52584. dashedLines.gapSize = gapSize;
  52585. return dashedLines;
  52586. };
  52587. /**
  52588. * Creates an extruded shape mesh.
  52589. * 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.
  52590. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52591. *
  52592. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52593. * 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
  52594. * extruded along the Z axis.
  52595. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52596. * 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.
  52597. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52598. * 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
  52599. * 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
  52600. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52602. * 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).
  52603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52604. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52606. */
  52607. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52608. if (scene === void 0) { scene = null; }
  52609. var path = options.path;
  52610. var shape = options.shape;
  52611. var scale = options.scale || 1;
  52612. var rotation = options.rotation || 0;
  52613. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52614. var updatable = options.updatable;
  52615. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52616. var instance = options.instance || null;
  52617. var invertUV = options.invertUV || false;
  52618. 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);
  52619. };
  52620. /**
  52621. * Creates an custom extruded shape mesh.
  52622. * 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.
  52623. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52624. *
  52625. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52626. * 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
  52627. * extruded along the Z axis.
  52628. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52629. * 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
  52630. * and the distance of this point from the begining of the path :
  52631. * ```javascript
  52632. * var rotationFunction = function(i, distance) {
  52633. * // do things
  52634. * return rotationValue; }
  52635. * ```
  52636. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52637. * 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
  52638. * and the distance of this point from the begining of the path :
  52639. * ```javascript
  52640. * var scaleFunction = function(i, distance) {
  52641. * // do things
  52642. * return scaleValue;}
  52643. * ```
  52644. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52645. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52646. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52647. * 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
  52648. * 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
  52649. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52651. * 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).
  52652. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52653. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52655. */
  52656. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52657. var path = options.path;
  52658. var shape = options.shape;
  52659. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52660. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52661. var ribbonCloseArray = options.ribbonCloseArray || false;
  52662. var ribbonClosePath = options.ribbonClosePath || false;
  52663. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52664. var updatable = options.updatable;
  52665. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52666. var instance = options.instance;
  52667. var invertUV = options.invertUV || false;
  52668. 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);
  52669. };
  52670. /**
  52671. * Creates lathe mesh.
  52672. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52673. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52674. *
  52675. * 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
  52676. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52677. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52678. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52679. * 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.
  52680. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52681. * 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
  52682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52683. * 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).
  52684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52685. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52687. */
  52688. MeshBuilder.CreateLathe = function (name, options, scene) {
  52689. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52690. var closed = (options.closed === undefined) ? true : options.closed;
  52691. var shape = options.shape;
  52692. var radius = options.radius || 1;
  52693. var tessellation = options.tessellation || 64;
  52694. var updatable = options.updatable;
  52695. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52696. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52697. var pi2 = Math.PI * 2;
  52698. var paths = new Array();
  52699. var invertUV = options.invertUV || false;
  52700. var i = 0;
  52701. var p = 0;
  52702. var step = pi2 / tessellation * arc;
  52703. var rotated;
  52704. var path = new Array();
  52705. ;
  52706. for (i = 0; i <= tessellation; i++) {
  52707. var path = [];
  52708. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52709. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52710. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52711. }
  52712. for (p = 0; p < shape.length; p++) {
  52713. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52714. path.push(rotated);
  52715. }
  52716. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52717. 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));
  52718. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52719. }
  52720. paths.push(path);
  52721. }
  52722. // lathe ribbon
  52723. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52724. return lathe;
  52725. };
  52726. /**
  52727. * Creates a plane mesh.
  52728. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52729. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52730. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52731. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52732. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52733. * 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).
  52734. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52736. */
  52737. MeshBuilder.CreatePlane = function (name, options, scene) {
  52738. var plane = new BABYLON.Mesh(name, scene);
  52739. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52740. plane._originalBuilderSideOrientation = options.sideOrientation;
  52741. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52742. vertexData.applyToMesh(plane, options.updatable);
  52743. if (options.sourcePlane) {
  52744. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52745. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52746. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52747. plane.rotate(vectorProduct, product);
  52748. }
  52749. return plane;
  52750. };
  52751. /**
  52752. * Creates a ground mesh.
  52753. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52754. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52755. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52757. */
  52758. MeshBuilder.CreateGround = function (name, options, scene) {
  52759. var ground = new BABYLON.GroundMesh(name, scene);
  52760. ground._setReady(false);
  52761. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52762. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52763. ground._width = options.width || 1;
  52764. ground._height = options.height || 1;
  52765. ground._maxX = ground._width / 2;
  52766. ground._maxZ = ground._height / 2;
  52767. ground._minX = -ground._maxX;
  52768. ground._minZ = -ground._maxZ;
  52769. var vertexData = BABYLON.VertexData.CreateGround(options);
  52770. vertexData.applyToMesh(ground, options.updatable);
  52771. ground._setReady(true);
  52772. return ground;
  52773. };
  52774. /**
  52775. * Creates a tiled ground mesh.
  52776. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52777. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52778. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52779. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52780. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52781. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52782. * numbers of subdivisions on the ground width and height of each tile.
  52783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52784. */
  52785. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52786. var tiledGround = new BABYLON.Mesh(name, scene);
  52787. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52788. vertexData.applyToMesh(tiledGround, options.updatable);
  52789. return tiledGround;
  52790. };
  52791. /**
  52792. * Creates a ground mesh from a height map.
  52793. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52794. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52795. * The parameter `url` sets the URL of the height map image resource.
  52796. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52797. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52798. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52799. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52800. * 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.
  52801. * 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).
  52802. * This function is passed the newly built mesh :
  52803. * ```javascript
  52804. * function(mesh) { // do things
  52805. * return; }
  52806. * ```
  52807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52808. */
  52809. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52810. var width = options.width || 10.0;
  52811. var height = options.height || 10.0;
  52812. var subdivisions = options.subdivisions || 1 | 0;
  52813. var minHeight = options.minHeight || 0.0;
  52814. var maxHeight = options.maxHeight || 1.0;
  52815. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52816. var updatable = options.updatable;
  52817. var onReady = options.onReady;
  52818. var ground = new BABYLON.GroundMesh(name, scene);
  52819. ground._subdivisionsX = subdivisions;
  52820. ground._subdivisionsY = subdivisions;
  52821. ground._width = width;
  52822. ground._height = height;
  52823. ground._maxX = ground._width / 2.0;
  52824. ground._maxZ = ground._height / 2.0;
  52825. ground._minX = -ground._maxX;
  52826. ground._minZ = -ground._maxZ;
  52827. ground._setReady(false);
  52828. var onload = function (img) {
  52829. // Getting height map data
  52830. var canvas = document.createElement("canvas");
  52831. var context = canvas.getContext("2d");
  52832. if (!context) {
  52833. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52834. }
  52835. if (scene.isDisposed) {
  52836. return;
  52837. }
  52838. var bufferWidth = img.width;
  52839. var bufferHeight = img.height;
  52840. canvas.width = bufferWidth;
  52841. canvas.height = bufferHeight;
  52842. context.drawImage(img, 0, 0);
  52843. // Create VertexData from map data
  52844. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52845. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52846. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52847. width: width, height: height,
  52848. subdivisions: subdivisions,
  52849. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52850. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52851. });
  52852. vertexData.applyToMesh(ground, updatable);
  52853. ground._setReady(true);
  52854. //execute ready callback, if set
  52855. if (onReady) {
  52856. onReady(ground);
  52857. }
  52858. };
  52859. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52860. return ground;
  52861. };
  52862. /**
  52863. * Creates a polygon mesh.
  52864. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52865. * 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.
  52866. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52868. * 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).
  52869. * Remember you can only change the shape positions, not their number when updating a polygon.
  52870. */
  52871. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52872. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52873. var shape = options.shape;
  52874. var holes = options.holes || [];
  52875. var depth = options.depth || 0;
  52876. var contours = [];
  52877. var hole = [];
  52878. for (var i = 0; i < shape.length; i++) {
  52879. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52880. }
  52881. var epsilon = 0.00000001;
  52882. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52883. contours.pop();
  52884. }
  52885. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52886. for (var hNb = 0; hNb < holes.length; hNb++) {
  52887. hole = [];
  52888. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52889. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52890. }
  52891. polygonTriangulation.addHole(hole);
  52892. }
  52893. var polygon = polygonTriangulation.build(options.updatable, depth);
  52894. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52895. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52896. vertexData.applyToMesh(polygon, options.updatable);
  52897. return polygon;
  52898. };
  52899. ;
  52900. /**
  52901. * Creates an extruded polygon mesh, with depth in the Y direction.
  52902. * 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).
  52903. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52904. */
  52905. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52906. return MeshBuilder.CreatePolygon(name, options, scene);
  52907. };
  52908. ;
  52909. /**
  52910. * Creates a tube mesh.
  52911. * 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.
  52912. *
  52913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52914. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52915. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52916. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52917. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52918. * 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.
  52919. * It must return a radius value (positive float) :
  52920. * ```javascript
  52921. * var radiusFunction = function(i, distance) {
  52922. * // do things
  52923. * return radius; }
  52924. * ```
  52925. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52926. * 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
  52927. * 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
  52928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52929. * 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).
  52930. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52931. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52933. */
  52934. MeshBuilder.CreateTube = function (name, options, scene) {
  52935. var path = options.path;
  52936. var instance = options.instance;
  52937. var radius = 1.0;
  52938. if (instance) {
  52939. radius = instance.radius;
  52940. }
  52941. if (options.radius !== undefined) {
  52942. radius = options.radius;
  52943. }
  52944. ;
  52945. var tessellation = options.tessellation || 64 | 0;
  52946. var radiusFunction = options.radiusFunction || null;
  52947. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52948. var invertUV = options.invertUV || false;
  52949. var updatable = options.updatable;
  52950. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52951. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52952. // tube geometry
  52953. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52954. var tangents = path3D.getTangents();
  52955. var normals = path3D.getNormals();
  52956. var distances = path3D.getDistances();
  52957. var pi2 = Math.PI * 2;
  52958. var step = pi2 / tessellation * arc;
  52959. var returnRadius = function () { return radius; };
  52960. var radiusFunctionFinal = radiusFunction || returnRadius;
  52961. var circlePath;
  52962. var rad;
  52963. var normal;
  52964. var rotated;
  52965. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52966. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52967. for (var i = 0; i < path.length; i++) {
  52968. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52969. circlePath = Array(); // current circle array
  52970. normal = normals[i]; // current normal
  52971. for (var t = 0; t < tessellation; t++) {
  52972. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52973. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52974. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52975. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52976. circlePath[t] = rotated;
  52977. }
  52978. circlePaths[index] = circlePath;
  52979. index++;
  52980. }
  52981. // cap
  52982. var capPath = function (nbPoints, pathIndex) {
  52983. var pointCap = Array();
  52984. for (var i = 0; i < nbPoints; i++) {
  52985. pointCap.push(path[pathIndex]);
  52986. }
  52987. return pointCap;
  52988. };
  52989. switch (cap) {
  52990. case BABYLON.Mesh.NO_CAP:
  52991. break;
  52992. case BABYLON.Mesh.CAP_START:
  52993. circlePaths[0] = capPath(tessellation, 0);
  52994. circlePaths[1] = circlePaths[2].slice(0);
  52995. break;
  52996. case BABYLON.Mesh.CAP_END:
  52997. circlePaths[index] = circlePaths[index - 1].slice(0);
  52998. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52999. break;
  53000. case BABYLON.Mesh.CAP_ALL:
  53001. circlePaths[0] = capPath(tessellation, 0);
  53002. circlePaths[1] = circlePaths[2].slice(0);
  53003. circlePaths[index] = circlePaths[index - 1].slice(0);
  53004. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  53005. break;
  53006. default:
  53007. break;
  53008. }
  53009. return circlePaths;
  53010. };
  53011. var path3D;
  53012. var pathArray;
  53013. if (instance) {
  53014. var arc = options.arc || instance.arc;
  53015. path3D = (instance.path3D).update(path);
  53016. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  53017. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  53018. instance.path3D = path3D;
  53019. instance.pathArray = pathArray;
  53020. instance.arc = arc;
  53021. instance.radius = radius;
  53022. return instance;
  53023. }
  53024. // tube creation
  53025. path3D = new BABYLON.Path3D(path);
  53026. var newPathArray = new Array();
  53027. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53028. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  53029. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  53030. tube.pathArray = pathArray;
  53031. tube.path3D = path3D;
  53032. tube.tessellation = tessellation;
  53033. tube.cap = cap;
  53034. tube.arc = options.arc;
  53035. tube.radius = radius;
  53036. return tube;
  53037. };
  53038. /**
  53039. * Creates a polyhedron mesh.
  53040. *
  53041. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  53042. * 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
  53043. * to choose the wanted type.
  53044. * The parameter `size` (positive float, default 1) sets the polygon size.
  53045. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  53046. * 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`.
  53047. * 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
  53048. * 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)`).
  53049. * 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
  53050. * 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.
  53051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53052. * 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).
  53053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53055. */
  53056. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  53057. var polyhedron = new BABYLON.Mesh(name, scene);
  53058. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53059. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  53060. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  53061. vertexData.applyToMesh(polyhedron, options.updatable);
  53062. return polyhedron;
  53063. };
  53064. /**
  53065. * Creates a decal mesh.
  53066. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  53067. * 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.
  53068. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  53069. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  53070. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  53071. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  53072. */
  53073. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  53074. var indices = sourceMesh.getIndices();
  53075. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53076. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53077. var position = options.position || BABYLON.Vector3.Zero();
  53078. var normal = options.normal || BABYLON.Vector3.Up();
  53079. var size = options.size || BABYLON.Vector3.One();
  53080. var angle = options.angle || 0;
  53081. // Getting correct rotation
  53082. if (!normal) {
  53083. var target = new BABYLON.Vector3(0, 0, 1);
  53084. var camera = sourceMesh.getScene().activeCamera;
  53085. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  53086. normal = camera.globalPosition.subtract(cameraWorldTarget);
  53087. }
  53088. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  53089. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  53090. var pitch = Math.atan2(normal.y, len);
  53091. // Matrix
  53092. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  53093. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  53094. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  53095. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  53096. var vertexData = new BABYLON.VertexData();
  53097. vertexData.indices = [];
  53098. vertexData.positions = [];
  53099. vertexData.normals = [];
  53100. vertexData.uvs = [];
  53101. var currentVertexDataIndex = 0;
  53102. var extractDecalVector3 = function (indexId) {
  53103. var result = new BABYLON.PositionNormalVertex();
  53104. if (!indices || !positions || !normals) {
  53105. return result;
  53106. }
  53107. var vertexId = indices[indexId];
  53108. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  53109. // Send vector to decal local world
  53110. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  53111. // Get normal
  53112. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  53113. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  53114. return result;
  53115. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  53116. var clip = function (vertices, axis) {
  53117. if (vertices.length === 0) {
  53118. return vertices;
  53119. }
  53120. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  53121. var clipVertices = function (v0, v1) {
  53122. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  53123. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  53124. };
  53125. var result = new Array();
  53126. for (var index = 0; index < vertices.length; index += 3) {
  53127. var v1Out;
  53128. var v2Out;
  53129. var v3Out;
  53130. var total = 0;
  53131. var nV1 = null;
  53132. var nV2 = null;
  53133. var nV3 = null;
  53134. var nV4 = null;
  53135. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  53136. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  53137. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  53138. v1Out = d1 > 0;
  53139. v2Out = d2 > 0;
  53140. v3Out = d3 > 0;
  53141. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  53142. switch (total) {
  53143. case 0:
  53144. result.push(vertices[index]);
  53145. result.push(vertices[index + 1]);
  53146. result.push(vertices[index + 2]);
  53147. break;
  53148. case 1:
  53149. if (v1Out) {
  53150. nV1 = vertices[index + 1];
  53151. nV2 = vertices[index + 2];
  53152. nV3 = clipVertices(vertices[index], nV1);
  53153. nV4 = clipVertices(vertices[index], nV2);
  53154. }
  53155. if (v2Out) {
  53156. nV1 = vertices[index];
  53157. nV2 = vertices[index + 2];
  53158. nV3 = clipVertices(vertices[index + 1], nV1);
  53159. nV4 = clipVertices(vertices[index + 1], nV2);
  53160. result.push(nV3);
  53161. result.push(nV2.clone());
  53162. result.push(nV1.clone());
  53163. result.push(nV2.clone());
  53164. result.push(nV3.clone());
  53165. result.push(nV4);
  53166. break;
  53167. }
  53168. if (v3Out) {
  53169. nV1 = vertices[index];
  53170. nV2 = vertices[index + 1];
  53171. nV3 = clipVertices(vertices[index + 2], nV1);
  53172. nV4 = clipVertices(vertices[index + 2], nV2);
  53173. }
  53174. if (nV1 && nV2 && nV3 && nV4) {
  53175. result.push(nV1.clone());
  53176. result.push(nV2.clone());
  53177. result.push(nV3);
  53178. result.push(nV4);
  53179. result.push(nV3.clone());
  53180. result.push(nV2.clone());
  53181. }
  53182. break;
  53183. case 2:
  53184. if (!v1Out) {
  53185. nV1 = vertices[index].clone();
  53186. nV2 = clipVertices(nV1, vertices[index + 1]);
  53187. nV3 = clipVertices(nV1, vertices[index + 2]);
  53188. result.push(nV1);
  53189. result.push(nV2);
  53190. result.push(nV3);
  53191. }
  53192. if (!v2Out) {
  53193. nV1 = vertices[index + 1].clone();
  53194. nV2 = clipVertices(nV1, vertices[index + 2]);
  53195. nV3 = clipVertices(nV1, vertices[index]);
  53196. result.push(nV1);
  53197. result.push(nV2);
  53198. result.push(nV3);
  53199. }
  53200. if (!v3Out) {
  53201. nV1 = vertices[index + 2].clone();
  53202. nV2 = clipVertices(nV1, vertices[index]);
  53203. nV3 = clipVertices(nV1, vertices[index + 1]);
  53204. result.push(nV1);
  53205. result.push(nV2);
  53206. result.push(nV3);
  53207. }
  53208. break;
  53209. case 3:
  53210. break;
  53211. }
  53212. }
  53213. return result;
  53214. };
  53215. for (var index = 0; index < indices.length; index += 3) {
  53216. var faceVertices = new Array();
  53217. faceVertices.push(extractDecalVector3(index));
  53218. faceVertices.push(extractDecalVector3(index + 1));
  53219. faceVertices.push(extractDecalVector3(index + 2));
  53220. // Clip
  53221. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  53222. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  53223. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  53224. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  53225. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  53226. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  53227. if (faceVertices.length === 0) {
  53228. continue;
  53229. }
  53230. // Add UVs and get back to world
  53231. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  53232. var vertex = faceVertices[vIndex];
  53233. //TODO check for Int32Array | Uint32Array | Uint16Array
  53234. vertexData.indices.push(currentVertexDataIndex);
  53235. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  53236. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  53237. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  53238. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  53239. currentVertexDataIndex++;
  53240. }
  53241. }
  53242. // Return mesh
  53243. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  53244. vertexData.applyToMesh(decal);
  53245. decal.position = position.clone();
  53246. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  53247. return decal;
  53248. };
  53249. // Privates
  53250. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53251. // extrusion geometry
  53252. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53253. var tangents = path3D.getTangents();
  53254. var normals = path3D.getNormals();
  53255. var binormals = path3D.getBinormals();
  53256. var distances = path3D.getDistances();
  53257. var angle = 0;
  53258. var returnScale = function () { return scale !== null ? scale : 1; };
  53259. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53260. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53261. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53262. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53263. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53264. for (var i = 0; i < curve.length; i++) {
  53265. var shapePath = new Array();
  53266. var angleStep = rotate(i, distances[i]);
  53267. var scaleRatio = scl(i, distances[i]);
  53268. for (var p = 0; p < shape.length; p++) {
  53269. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53270. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53271. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53272. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53273. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53274. shapePath[p] = rotated;
  53275. }
  53276. shapePaths[index] = shapePath;
  53277. angle += angleStep;
  53278. index++;
  53279. }
  53280. // cap
  53281. var capPath = function (shapePath) {
  53282. var pointCap = Array();
  53283. var barycenter = BABYLON.Vector3.Zero();
  53284. var i;
  53285. for (i = 0; i < shapePath.length; i++) {
  53286. barycenter.addInPlace(shapePath[i]);
  53287. }
  53288. barycenter.scaleInPlace(1.0 / shapePath.length);
  53289. for (i = 0; i < shapePath.length; i++) {
  53290. pointCap.push(barycenter);
  53291. }
  53292. return pointCap;
  53293. };
  53294. switch (cap) {
  53295. case BABYLON.Mesh.NO_CAP:
  53296. break;
  53297. case BABYLON.Mesh.CAP_START:
  53298. shapePaths[0] = capPath(shapePaths[2]);
  53299. shapePaths[1] = shapePaths[2];
  53300. break;
  53301. case BABYLON.Mesh.CAP_END:
  53302. shapePaths[index] = shapePaths[index - 1];
  53303. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53304. break;
  53305. case BABYLON.Mesh.CAP_ALL:
  53306. shapePaths[0] = capPath(shapePaths[2]);
  53307. shapePaths[1] = shapePaths[2];
  53308. shapePaths[index] = shapePaths[index - 1];
  53309. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53310. break;
  53311. default:
  53312. break;
  53313. }
  53314. return shapePaths;
  53315. };
  53316. var path3D;
  53317. var pathArray;
  53318. if (instance) {
  53319. path3D = (instance.path3D).update(curve);
  53320. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53321. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53322. return instance;
  53323. }
  53324. // extruded shape creation
  53325. path3D = new BABYLON.Path3D(curve);
  53326. var newShapePaths = new Array();
  53327. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53328. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53329. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53330. extrudedGeneric.pathArray = pathArray;
  53331. extrudedGeneric.path3D = path3D;
  53332. extrudedGeneric.cap = cap;
  53333. return extrudedGeneric;
  53334. };
  53335. return MeshBuilder;
  53336. }());
  53337. BABYLON.MeshBuilder = MeshBuilder;
  53338. })(BABYLON || (BABYLON = {}));
  53339. //# sourceMappingURL=babylon.meshBuilder.js.map
  53340. var BABYLON;
  53341. (function (BABYLON) {
  53342. var AudioEngine = /** @class */ (function () {
  53343. function AudioEngine() {
  53344. this._audioContext = null;
  53345. this._audioContextInitialized = false;
  53346. this.canUseWebAudio = false;
  53347. this.WarnedWebAudioUnsupported = false;
  53348. this.unlocked = false;
  53349. this.isMP3supported = false;
  53350. this.isOGGsupported = false;
  53351. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53352. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53353. this.canUseWebAudio = true;
  53354. }
  53355. var audioElem = document.createElement('audio');
  53356. try {
  53357. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53358. this.isMP3supported = true;
  53359. }
  53360. }
  53361. catch (e) {
  53362. // protect error during capability check.
  53363. }
  53364. try {
  53365. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53366. this.isOGGsupported = true;
  53367. }
  53368. }
  53369. catch (e) {
  53370. // protect error during capability check.
  53371. }
  53372. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53373. this._unlockiOSaudio();
  53374. }
  53375. else {
  53376. this.unlocked = true;
  53377. }
  53378. }
  53379. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53380. get: function () {
  53381. if (!this._audioContextInitialized) {
  53382. this._initializeAudioContext();
  53383. }
  53384. return this._audioContext;
  53385. },
  53386. enumerable: true,
  53387. configurable: true
  53388. });
  53389. AudioEngine.prototype._unlockiOSaudio = function () {
  53390. var _this = this;
  53391. var unlockaudio = function () {
  53392. if (!_this.audioContext) {
  53393. return;
  53394. }
  53395. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53396. var source = _this.audioContext.createBufferSource();
  53397. source.buffer = buffer;
  53398. source.connect(_this.audioContext.destination);
  53399. source.start(0);
  53400. setTimeout(function () {
  53401. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53402. _this.unlocked = true;
  53403. window.removeEventListener('touchend', unlockaudio, false);
  53404. if (_this.onAudioUnlocked) {
  53405. _this.onAudioUnlocked();
  53406. }
  53407. }
  53408. }, 0);
  53409. };
  53410. window.addEventListener('touchend', unlockaudio, false);
  53411. };
  53412. AudioEngine.prototype._initializeAudioContext = function () {
  53413. try {
  53414. if (this.canUseWebAudio) {
  53415. this._audioContext = new AudioContext();
  53416. // create a global volume gain node
  53417. this.masterGain = this._audioContext.createGain();
  53418. this.masterGain.gain.value = 1;
  53419. this.masterGain.connect(this._audioContext.destination);
  53420. this._audioContextInitialized = true;
  53421. }
  53422. }
  53423. catch (e) {
  53424. this.canUseWebAudio = false;
  53425. BABYLON.Tools.Error("Web Audio: " + e.message);
  53426. }
  53427. };
  53428. AudioEngine.prototype.dispose = function () {
  53429. if (this.canUseWebAudio && this._audioContextInitialized) {
  53430. if (this._connectedAnalyser && this._audioContext) {
  53431. this._connectedAnalyser.stopDebugCanvas();
  53432. this._connectedAnalyser.dispose();
  53433. this.masterGain.disconnect();
  53434. this.masterGain.connect(this._audioContext.destination);
  53435. this._connectedAnalyser = null;
  53436. }
  53437. this.masterGain.gain.value = 1;
  53438. }
  53439. this.WarnedWebAudioUnsupported = false;
  53440. };
  53441. AudioEngine.prototype.getGlobalVolume = function () {
  53442. if (this.canUseWebAudio && this._audioContextInitialized) {
  53443. return this.masterGain.gain.value;
  53444. }
  53445. else {
  53446. return -1;
  53447. }
  53448. };
  53449. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53450. if (this.canUseWebAudio && this._audioContextInitialized) {
  53451. this.masterGain.gain.value = newVolume;
  53452. }
  53453. };
  53454. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53455. if (this._connectedAnalyser) {
  53456. this._connectedAnalyser.stopDebugCanvas();
  53457. }
  53458. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53459. this._connectedAnalyser = analyser;
  53460. this.masterGain.disconnect();
  53461. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53462. }
  53463. };
  53464. return AudioEngine;
  53465. }());
  53466. BABYLON.AudioEngine = AudioEngine;
  53467. })(BABYLON || (BABYLON = {}));
  53468. //# sourceMappingURL=babylon.audioEngine.js.map
  53469. var BABYLON;
  53470. (function (BABYLON) {
  53471. var Sound = /** @class */ (function () {
  53472. /**
  53473. * Create a sound and attach it to a scene
  53474. * @param name Name of your sound
  53475. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53476. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53477. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53478. */
  53479. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53480. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53481. var _this = this;
  53482. this.autoplay = false;
  53483. this.loop = false;
  53484. this.useCustomAttenuation = false;
  53485. this.spatialSound = false;
  53486. this.refDistance = 1;
  53487. this.rolloffFactor = 1;
  53488. this.maxDistance = 100;
  53489. this.distanceModel = "linear";
  53490. this._panningModel = "equalpower";
  53491. this._playbackRate = 1;
  53492. this._streaming = false;
  53493. this._startTime = 0;
  53494. this._startOffset = 0;
  53495. this._position = BABYLON.Vector3.Zero();
  53496. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53497. this._volume = 1;
  53498. this._isReadyToPlay = false;
  53499. this.isPlaying = false;
  53500. this.isPaused = false;
  53501. this._isDirectional = false;
  53502. // Used if you'd like to create a directional sound.
  53503. // If not set, the sound will be omnidirectional
  53504. this._coneInnerAngle = 360;
  53505. this._coneOuterAngle = 360;
  53506. this._coneOuterGain = 0;
  53507. this._isOutputConnected = false;
  53508. this._urlType = "Unknown";
  53509. this.name = name;
  53510. this._scene = scene;
  53511. this._readyToPlayCallback = readyToPlayCallback;
  53512. // Default custom attenuation function is a linear attenuation
  53513. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53514. if (currentDistance < maxDistance) {
  53515. return currentVolume * (1 - currentDistance / maxDistance);
  53516. }
  53517. else {
  53518. return 0;
  53519. }
  53520. };
  53521. if (options) {
  53522. this.autoplay = options.autoplay || false;
  53523. this.loop = options.loop || false;
  53524. // if volume === 0, we need another way to check this option
  53525. if (options.volume !== undefined) {
  53526. this._volume = options.volume;
  53527. }
  53528. this.spatialSound = options.spatialSound || false;
  53529. this.maxDistance = options.maxDistance || 100;
  53530. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53531. this.rolloffFactor = options.rolloffFactor || 1;
  53532. this.refDistance = options.refDistance || 1;
  53533. this.distanceModel = options.distanceModel || "linear";
  53534. this._playbackRate = options.playbackRate || 1;
  53535. this._streaming = options.streaming || false;
  53536. }
  53537. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53538. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53539. this._soundGain.gain.value = this._volume;
  53540. this._inputAudioNode = this._soundGain;
  53541. this._ouputAudioNode = this._soundGain;
  53542. if (this.spatialSound) {
  53543. this._createSpatialParameters();
  53544. }
  53545. this._scene.mainSoundTrack.AddSound(this);
  53546. var validParameter = true;
  53547. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53548. if (urlOrArrayBuffer) {
  53549. if (typeof (urlOrArrayBuffer) === "string")
  53550. this._urlType = "String";
  53551. if (Array.isArray(urlOrArrayBuffer))
  53552. this._urlType = "Array";
  53553. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53554. this._urlType = "ArrayBuffer";
  53555. var urls = [];
  53556. var codecSupportedFound = false;
  53557. switch (this._urlType) {
  53558. case "ArrayBuffer":
  53559. if (urlOrArrayBuffer.byteLength > 0) {
  53560. codecSupportedFound = true;
  53561. this._soundLoaded(urlOrArrayBuffer);
  53562. }
  53563. break;
  53564. case "String":
  53565. urls.push(urlOrArrayBuffer);
  53566. case "Array":
  53567. if (urls.length === 0)
  53568. urls = urlOrArrayBuffer;
  53569. // If we found a supported format, we load it immediately and stop the loop
  53570. for (var i = 0; i < urls.length; i++) {
  53571. var url = urls[i];
  53572. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53573. codecSupportedFound = true;
  53574. }
  53575. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53576. codecSupportedFound = true;
  53577. }
  53578. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53579. codecSupportedFound = true;
  53580. }
  53581. if (url.indexOf("blob:") !== -1) {
  53582. codecSupportedFound = true;
  53583. }
  53584. if (codecSupportedFound) {
  53585. // Loading sound using XHR2
  53586. if (!this._streaming) {
  53587. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53588. }
  53589. else {
  53590. this._htmlAudioElement = new Audio(url);
  53591. this._htmlAudioElement.controls = false;
  53592. this._htmlAudioElement.loop = this.loop;
  53593. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53594. this._htmlAudioElement.preload = "auto";
  53595. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53596. _this._isReadyToPlay = true;
  53597. if (_this.autoplay) {
  53598. _this.play();
  53599. }
  53600. if (_this._readyToPlayCallback) {
  53601. _this._readyToPlayCallback();
  53602. }
  53603. });
  53604. document.body.appendChild(this._htmlAudioElement);
  53605. }
  53606. break;
  53607. }
  53608. }
  53609. break;
  53610. default:
  53611. validParameter = false;
  53612. break;
  53613. }
  53614. if (!validParameter) {
  53615. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53616. }
  53617. else {
  53618. if (!codecSupportedFound) {
  53619. this._isReadyToPlay = true;
  53620. // Simulating a ready to play event to avoid breaking code path
  53621. if (this._readyToPlayCallback) {
  53622. window.setTimeout(function () {
  53623. if (_this._readyToPlayCallback) {
  53624. _this._readyToPlayCallback();
  53625. }
  53626. }, 1000);
  53627. }
  53628. }
  53629. }
  53630. }
  53631. }
  53632. else {
  53633. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53634. this._scene.mainSoundTrack.AddSound(this);
  53635. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53636. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53637. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53638. }
  53639. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53640. if (this._readyToPlayCallback) {
  53641. window.setTimeout(function () {
  53642. if (_this._readyToPlayCallback) {
  53643. _this._readyToPlayCallback();
  53644. }
  53645. }, 1000);
  53646. }
  53647. }
  53648. }
  53649. Sound.prototype.dispose = function () {
  53650. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53651. if (this.isPlaying) {
  53652. this.stop();
  53653. }
  53654. this._isReadyToPlay = false;
  53655. if (this.soundTrackId === -1) {
  53656. this._scene.mainSoundTrack.RemoveSound(this);
  53657. }
  53658. else {
  53659. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53660. }
  53661. if (this._soundGain) {
  53662. this._soundGain.disconnect();
  53663. this._soundGain = null;
  53664. }
  53665. if (this._soundPanner) {
  53666. this._soundPanner.disconnect();
  53667. this._soundPanner = null;
  53668. }
  53669. if (this._soundSource) {
  53670. this._soundSource.disconnect();
  53671. this._soundSource = null;
  53672. }
  53673. this._audioBuffer = null;
  53674. if (this._htmlAudioElement) {
  53675. this._htmlAudioElement.pause();
  53676. this._htmlAudioElement.src = "";
  53677. document.body.removeChild(this._htmlAudioElement);
  53678. }
  53679. if (this._connectedMesh && this._registerFunc) {
  53680. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53681. this._connectedMesh = null;
  53682. }
  53683. }
  53684. };
  53685. Sound.prototype.isReady = function () {
  53686. return this._isReadyToPlay;
  53687. };
  53688. Sound.prototype._soundLoaded = function (audioData) {
  53689. var _this = this;
  53690. if (!BABYLON.Engine.audioEngine.audioContext) {
  53691. return;
  53692. }
  53693. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53694. _this._audioBuffer = buffer;
  53695. _this._isReadyToPlay = true;
  53696. if (_this.autoplay) {
  53697. _this.play();
  53698. }
  53699. if (_this._readyToPlayCallback) {
  53700. _this._readyToPlayCallback();
  53701. }
  53702. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53703. };
  53704. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53706. this._audioBuffer = audioBuffer;
  53707. this._isReadyToPlay = true;
  53708. }
  53709. };
  53710. Sound.prototype.updateOptions = function (options) {
  53711. if (options) {
  53712. this.loop = options.loop || this.loop;
  53713. this.maxDistance = options.maxDistance || this.maxDistance;
  53714. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53715. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53716. this.refDistance = options.refDistance || this.refDistance;
  53717. this.distanceModel = options.distanceModel || this.distanceModel;
  53718. this._playbackRate = options.playbackRate || this._playbackRate;
  53719. this._updateSpatialParameters();
  53720. if (this.isPlaying) {
  53721. if (this._streaming) {
  53722. this._htmlAudioElement.playbackRate = this._playbackRate;
  53723. }
  53724. else {
  53725. if (this._soundSource) {
  53726. this._soundSource.playbackRate.value = this._playbackRate;
  53727. }
  53728. }
  53729. }
  53730. }
  53731. };
  53732. Sound.prototype._createSpatialParameters = function () {
  53733. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53734. if (this._scene.headphone) {
  53735. this._panningModel = "HRTF";
  53736. }
  53737. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53738. this._updateSpatialParameters();
  53739. this._soundPanner.connect(this._ouputAudioNode);
  53740. this._inputAudioNode = this._soundPanner;
  53741. }
  53742. };
  53743. Sound.prototype._updateSpatialParameters = function () {
  53744. if (this.spatialSound && this._soundPanner) {
  53745. if (this.useCustomAttenuation) {
  53746. // Tricks to disable in a way embedded Web Audio attenuation
  53747. this._soundPanner.distanceModel = "linear";
  53748. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53749. this._soundPanner.refDistance = 1;
  53750. this._soundPanner.rolloffFactor = 1;
  53751. this._soundPanner.panningModel = this._panningModel;
  53752. }
  53753. else {
  53754. this._soundPanner.distanceModel = this.distanceModel;
  53755. this._soundPanner.maxDistance = this.maxDistance;
  53756. this._soundPanner.refDistance = this.refDistance;
  53757. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53758. this._soundPanner.panningModel = this._panningModel;
  53759. }
  53760. }
  53761. };
  53762. Sound.prototype.switchPanningModelToHRTF = function () {
  53763. this._panningModel = "HRTF";
  53764. this._switchPanningModel();
  53765. };
  53766. Sound.prototype.switchPanningModelToEqualPower = function () {
  53767. this._panningModel = "equalpower";
  53768. this._switchPanningModel();
  53769. };
  53770. Sound.prototype._switchPanningModel = function () {
  53771. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53772. this._soundPanner.panningModel = this._panningModel;
  53773. }
  53774. };
  53775. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53776. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53777. if (this._isOutputConnected) {
  53778. this._ouputAudioNode.disconnect();
  53779. }
  53780. this._ouputAudioNode.connect(soundTrackAudioNode);
  53781. this._isOutputConnected = true;
  53782. }
  53783. };
  53784. /**
  53785. * Transform this sound into a directional source
  53786. * @param coneInnerAngle Size of the inner cone in degree
  53787. * @param coneOuterAngle Size of the outer cone in degree
  53788. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53789. */
  53790. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53791. if (coneOuterAngle < coneInnerAngle) {
  53792. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53793. return;
  53794. }
  53795. this._coneInnerAngle = coneInnerAngle;
  53796. this._coneOuterAngle = coneOuterAngle;
  53797. this._coneOuterGain = coneOuterGain;
  53798. this._isDirectional = true;
  53799. if (this.isPlaying && this.loop) {
  53800. this.stop();
  53801. this.play();
  53802. }
  53803. };
  53804. Sound.prototype.setPosition = function (newPosition) {
  53805. this._position = newPosition;
  53806. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53807. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53808. }
  53809. };
  53810. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53811. this._localDirection = newLocalDirection;
  53812. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53813. this._updateDirection();
  53814. }
  53815. };
  53816. Sound.prototype._updateDirection = function () {
  53817. if (!this._connectedMesh || !this._soundPanner) {
  53818. return;
  53819. }
  53820. var mat = this._connectedMesh.getWorldMatrix();
  53821. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53822. direction.normalize();
  53823. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53824. };
  53825. Sound.prototype.updateDistanceFromListener = function () {
  53826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53827. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53828. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53829. }
  53830. };
  53831. Sound.prototype.setAttenuationFunction = function (callback) {
  53832. this._customAttenuationFunction = callback;
  53833. };
  53834. /**
  53835. * Play the sound
  53836. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53837. * @param offset (optional) Start the sound setting it at a specific time
  53838. */
  53839. Sound.prototype.play = function (time, offset) {
  53840. var _this = this;
  53841. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53842. try {
  53843. if (this._startOffset < 0) {
  53844. time = -this._startOffset;
  53845. this._startOffset = 0;
  53846. }
  53847. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53848. if (!this._soundSource || !this._streamingSource) {
  53849. if (this.spatialSound && this._soundPanner) {
  53850. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53851. if (this._isDirectional) {
  53852. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53853. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53854. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53855. if (this._connectedMesh) {
  53856. this._updateDirection();
  53857. }
  53858. else {
  53859. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53860. }
  53861. }
  53862. }
  53863. }
  53864. if (this._streaming) {
  53865. if (!this._streamingSource) {
  53866. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53867. this._htmlAudioElement.onended = function () { _this._onended(); };
  53868. this._htmlAudioElement.playbackRate = this._playbackRate;
  53869. }
  53870. this._streamingSource.disconnect();
  53871. this._streamingSource.connect(this._inputAudioNode);
  53872. this._htmlAudioElement.play();
  53873. }
  53874. else {
  53875. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53876. this._soundSource.buffer = this._audioBuffer;
  53877. this._soundSource.connect(this._inputAudioNode);
  53878. this._soundSource.loop = this.loop;
  53879. this._soundSource.playbackRate.value = this._playbackRate;
  53880. this._soundSource.onended = function () { _this._onended(); };
  53881. if (this._soundSource.buffer) {
  53882. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53883. }
  53884. }
  53885. this._startTime = startTime;
  53886. this.isPlaying = true;
  53887. this.isPaused = false;
  53888. }
  53889. catch (ex) {
  53890. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53891. }
  53892. }
  53893. };
  53894. Sound.prototype._onended = function () {
  53895. this.isPlaying = false;
  53896. if (this.onended) {
  53897. this.onended();
  53898. }
  53899. };
  53900. /**
  53901. * Stop the sound
  53902. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53903. */
  53904. Sound.prototype.stop = function (time) {
  53905. if (this.isPlaying) {
  53906. if (this._streaming) {
  53907. this._htmlAudioElement.pause();
  53908. // Test needed for Firefox or it will generate an Invalid State Error
  53909. if (this._htmlAudioElement.currentTime > 0) {
  53910. this._htmlAudioElement.currentTime = 0;
  53911. }
  53912. }
  53913. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53914. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53915. this._soundSource.stop(stopTime);
  53916. this._soundSource.onended = function () { };
  53917. if (!this.isPaused) {
  53918. this._startOffset = 0;
  53919. }
  53920. }
  53921. this.isPlaying = false;
  53922. }
  53923. };
  53924. Sound.prototype.pause = function () {
  53925. if (this.isPlaying) {
  53926. this.isPaused = true;
  53927. if (this._streaming) {
  53928. this._htmlAudioElement.pause();
  53929. }
  53930. else if (BABYLON.Engine.audioEngine.audioContext) {
  53931. this.stop(0);
  53932. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53933. }
  53934. }
  53935. };
  53936. Sound.prototype.setVolume = function (newVolume, time) {
  53937. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53938. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53939. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53940. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53941. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53942. }
  53943. else {
  53944. this._soundGain.gain.value = newVolume;
  53945. }
  53946. }
  53947. this._volume = newVolume;
  53948. };
  53949. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53950. this._playbackRate = newPlaybackRate;
  53951. if (this.isPlaying) {
  53952. if (this._streaming) {
  53953. this._htmlAudioElement.playbackRate = this._playbackRate;
  53954. }
  53955. else if (this._soundSource) {
  53956. this._soundSource.playbackRate.value = this._playbackRate;
  53957. }
  53958. }
  53959. };
  53960. Sound.prototype.getVolume = function () {
  53961. return this._volume;
  53962. };
  53963. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53964. var _this = this;
  53965. if (this._connectedMesh && this._registerFunc) {
  53966. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53967. this._registerFunc = null;
  53968. }
  53969. this._connectedMesh = meshToConnectTo;
  53970. if (!this.spatialSound) {
  53971. this.spatialSound = true;
  53972. this._createSpatialParameters();
  53973. if (this.isPlaying && this.loop) {
  53974. this.stop();
  53975. this.play();
  53976. }
  53977. }
  53978. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53979. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53980. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53981. };
  53982. Sound.prototype.detachFromMesh = function () {
  53983. if (this._connectedMesh && this._registerFunc) {
  53984. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53985. this._registerFunc = null;
  53986. this._connectedMesh = null;
  53987. }
  53988. };
  53989. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53990. if (!node.getBoundingInfo) {
  53991. return;
  53992. }
  53993. var mesh = node;
  53994. var boundingInfo = mesh.getBoundingInfo();
  53995. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53996. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53997. this._updateDirection();
  53998. }
  53999. };
  54000. Sound.prototype.clone = function () {
  54001. var _this = this;
  54002. if (!this._streaming) {
  54003. var setBufferAndRun = function () {
  54004. if (_this._isReadyToPlay) {
  54005. clonedSound._audioBuffer = _this.getAudioBuffer();
  54006. clonedSound._isReadyToPlay = true;
  54007. if (clonedSound.autoplay) {
  54008. clonedSound.play();
  54009. }
  54010. }
  54011. else {
  54012. window.setTimeout(setBufferAndRun, 300);
  54013. }
  54014. };
  54015. var currentOptions = {
  54016. autoplay: this.autoplay, loop: this.loop,
  54017. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  54018. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  54019. refDistance: this.refDistance, distanceModel: this.distanceModel
  54020. };
  54021. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  54022. if (this.useCustomAttenuation) {
  54023. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  54024. }
  54025. clonedSound.setPosition(this._position);
  54026. clonedSound.setPlaybackRate(this._playbackRate);
  54027. setBufferAndRun();
  54028. return clonedSound;
  54029. }
  54030. else {
  54031. return null;
  54032. }
  54033. };
  54034. Sound.prototype.getAudioBuffer = function () {
  54035. return this._audioBuffer;
  54036. };
  54037. Sound.prototype.serialize = function () {
  54038. var serializationObject = {
  54039. name: this.name,
  54040. url: this.name,
  54041. autoplay: this.autoplay,
  54042. loop: this.loop,
  54043. volume: this._volume,
  54044. spatialSound: this.spatialSound,
  54045. maxDistance: this.maxDistance,
  54046. rolloffFactor: this.rolloffFactor,
  54047. refDistance: this.refDistance,
  54048. distanceModel: this.distanceModel,
  54049. playbackRate: this._playbackRate,
  54050. panningModel: this._panningModel,
  54051. soundTrackId: this.soundTrackId
  54052. };
  54053. if (this.spatialSound) {
  54054. if (this._connectedMesh)
  54055. serializationObject.connectedMeshId = this._connectedMesh.id;
  54056. serializationObject.position = this._position.asArray();
  54057. serializationObject.refDistance = this.refDistance;
  54058. serializationObject.distanceModel = this.distanceModel;
  54059. serializationObject.isDirectional = this._isDirectional;
  54060. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  54061. serializationObject.coneInnerAngle = this._coneInnerAngle;
  54062. serializationObject.coneOuterAngle = this._coneOuterAngle;
  54063. serializationObject.coneOuterGain = this._coneOuterGain;
  54064. }
  54065. return serializationObject;
  54066. };
  54067. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  54068. var soundName = parsedSound.name;
  54069. var soundUrl;
  54070. if (parsedSound.url) {
  54071. soundUrl = rootUrl + parsedSound.url;
  54072. }
  54073. else {
  54074. soundUrl = rootUrl + soundName;
  54075. }
  54076. var options = {
  54077. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  54078. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  54079. rolloffFactor: parsedSound.rolloffFactor,
  54080. refDistance: parsedSound.refDistance,
  54081. distanceModel: parsedSound.distanceModel,
  54082. playbackRate: parsedSound.playbackRate
  54083. };
  54084. var newSound;
  54085. if (!sourceSound) {
  54086. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  54087. scene._addPendingData(newSound);
  54088. }
  54089. else {
  54090. var setBufferAndRun = function () {
  54091. if (sourceSound._isReadyToPlay) {
  54092. newSound._audioBuffer = sourceSound.getAudioBuffer();
  54093. newSound._isReadyToPlay = true;
  54094. if (newSound.autoplay) {
  54095. newSound.play();
  54096. }
  54097. }
  54098. else {
  54099. window.setTimeout(setBufferAndRun, 300);
  54100. }
  54101. };
  54102. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  54103. setBufferAndRun();
  54104. }
  54105. if (parsedSound.position) {
  54106. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  54107. newSound.setPosition(soundPosition);
  54108. }
  54109. if (parsedSound.isDirectional) {
  54110. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  54111. if (parsedSound.localDirectionToMesh) {
  54112. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  54113. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  54114. }
  54115. }
  54116. if (parsedSound.connectedMeshId) {
  54117. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  54118. if (connectedMesh) {
  54119. newSound.attachToMesh(connectedMesh);
  54120. }
  54121. }
  54122. return newSound;
  54123. };
  54124. return Sound;
  54125. }());
  54126. BABYLON.Sound = Sound;
  54127. })(BABYLON || (BABYLON = {}));
  54128. //# sourceMappingURL=babylon.sound.js.map
  54129. var BABYLON;
  54130. (function (BABYLON) {
  54131. var SoundTrack = /** @class */ (function () {
  54132. function SoundTrack(scene, options) {
  54133. this.id = -1;
  54134. this._isMainTrack = false;
  54135. this._isInitialized = false;
  54136. this._scene = scene;
  54137. this.soundCollection = new Array();
  54138. this._options = options;
  54139. if (!this._isMainTrack) {
  54140. this._scene.soundTracks.push(this);
  54141. this.id = this._scene.soundTracks.length - 1;
  54142. }
  54143. }
  54144. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  54145. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54146. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  54147. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  54148. if (this._options) {
  54149. if (this._options.volume) {
  54150. this._outputAudioNode.gain.value = this._options.volume;
  54151. }
  54152. if (this._options.mainTrack) {
  54153. this._isMainTrack = this._options.mainTrack;
  54154. }
  54155. }
  54156. this._isInitialized = true;
  54157. }
  54158. };
  54159. SoundTrack.prototype.dispose = function () {
  54160. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54161. if (this._connectedAnalyser) {
  54162. this._connectedAnalyser.stopDebugCanvas();
  54163. }
  54164. while (this.soundCollection.length) {
  54165. this.soundCollection[0].dispose();
  54166. }
  54167. if (this._outputAudioNode) {
  54168. this._outputAudioNode.disconnect();
  54169. }
  54170. this._outputAudioNode = null;
  54171. }
  54172. };
  54173. SoundTrack.prototype.AddSound = function (sound) {
  54174. if (!this._isInitialized) {
  54175. this._initializeSoundTrackAudioGraph();
  54176. }
  54177. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54178. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  54179. }
  54180. if (sound.soundTrackId) {
  54181. if (sound.soundTrackId === -1) {
  54182. this._scene.mainSoundTrack.RemoveSound(sound);
  54183. }
  54184. else {
  54185. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  54186. }
  54187. }
  54188. this.soundCollection.push(sound);
  54189. sound.soundTrackId = this.id;
  54190. };
  54191. SoundTrack.prototype.RemoveSound = function (sound) {
  54192. var index = this.soundCollection.indexOf(sound);
  54193. if (index !== -1) {
  54194. this.soundCollection.splice(index, 1);
  54195. }
  54196. };
  54197. SoundTrack.prototype.setVolume = function (newVolume) {
  54198. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54199. this._outputAudioNode.gain.value = newVolume;
  54200. }
  54201. };
  54202. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  54203. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54204. for (var i = 0; i < this.soundCollection.length; i++) {
  54205. this.soundCollection[i].switchPanningModelToHRTF();
  54206. }
  54207. }
  54208. };
  54209. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  54210. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54211. for (var i = 0; i < this.soundCollection.length; i++) {
  54212. this.soundCollection[i].switchPanningModelToEqualPower();
  54213. }
  54214. }
  54215. };
  54216. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  54217. if (this._connectedAnalyser) {
  54218. this._connectedAnalyser.stopDebugCanvas();
  54219. }
  54220. this._connectedAnalyser = analyser;
  54221. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54222. this._outputAudioNode.disconnect();
  54223. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  54224. }
  54225. };
  54226. return SoundTrack;
  54227. }());
  54228. BABYLON.SoundTrack = SoundTrack;
  54229. })(BABYLON || (BABYLON = {}));
  54230. //# sourceMappingURL=babylon.soundtrack.js.map
  54231. var BABYLON;
  54232. (function (BABYLON) {
  54233. var Analyser = /** @class */ (function () {
  54234. function Analyser(scene) {
  54235. this.SMOOTHING = 0.75;
  54236. this.FFT_SIZE = 512;
  54237. this.BARGRAPHAMPLITUDE = 256;
  54238. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54239. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54240. this._scene = scene;
  54241. this._audioEngine = BABYLON.Engine.audioEngine;
  54242. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  54243. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54244. this._webAudioAnalyser.minDecibels = -140;
  54245. this._webAudioAnalyser.maxDecibels = 0;
  54246. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54247. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54248. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54249. }
  54250. }
  54251. Analyser.prototype.getFrequencyBinCount = function () {
  54252. if (this._audioEngine.canUseWebAudio) {
  54253. return this._webAudioAnalyser.frequencyBinCount;
  54254. }
  54255. else {
  54256. return 0;
  54257. }
  54258. };
  54259. Analyser.prototype.getByteFrequencyData = function () {
  54260. if (this._audioEngine.canUseWebAudio) {
  54261. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54262. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54263. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54264. }
  54265. return this._byteFreqs;
  54266. };
  54267. Analyser.prototype.getByteTimeDomainData = function () {
  54268. if (this._audioEngine.canUseWebAudio) {
  54269. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54270. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54271. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54272. }
  54273. return this._byteTime;
  54274. };
  54275. Analyser.prototype.getFloatFrequencyData = function () {
  54276. if (this._audioEngine.canUseWebAudio) {
  54277. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54278. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54279. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54280. }
  54281. return this._floatFreqs;
  54282. };
  54283. Analyser.prototype.drawDebugCanvas = function () {
  54284. var _this = this;
  54285. if (this._audioEngine.canUseWebAudio) {
  54286. if (!this._debugCanvas) {
  54287. this._debugCanvas = document.createElement("canvas");
  54288. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54289. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54290. this._debugCanvas.style.position = "absolute";
  54291. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54292. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54293. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54294. document.body.appendChild(this._debugCanvas);
  54295. this._registerFunc = function () {
  54296. _this.drawDebugCanvas();
  54297. };
  54298. this._scene.registerBeforeRender(this._registerFunc);
  54299. }
  54300. if (this._registerFunc && this._debugCanvasContext) {
  54301. var workingArray = this.getByteFrequencyData();
  54302. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54303. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54304. // Draw the frequency domain chart.
  54305. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54306. var value = workingArray[i];
  54307. var percent = value / this.BARGRAPHAMPLITUDE;
  54308. var height = this.DEBUGCANVASSIZE.height * percent;
  54309. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54310. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54311. var hue = i / this.getFrequencyBinCount() * 360;
  54312. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54313. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54314. }
  54315. }
  54316. }
  54317. };
  54318. Analyser.prototype.stopDebugCanvas = function () {
  54319. if (this._debugCanvas) {
  54320. if (this._registerFunc) {
  54321. this._scene.unregisterBeforeRender(this._registerFunc);
  54322. this._registerFunc = null;
  54323. }
  54324. document.body.removeChild(this._debugCanvas);
  54325. this._debugCanvas = null;
  54326. this._debugCanvasContext = null;
  54327. }
  54328. };
  54329. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54330. if (this._audioEngine.canUseWebAudio) {
  54331. inputAudioNode.connect(this._webAudioAnalyser);
  54332. this._webAudioAnalyser.connect(outputAudioNode);
  54333. }
  54334. };
  54335. Analyser.prototype.dispose = function () {
  54336. if (this._audioEngine.canUseWebAudio) {
  54337. this._webAudioAnalyser.disconnect();
  54338. }
  54339. };
  54340. return Analyser;
  54341. }());
  54342. BABYLON.Analyser = Analyser;
  54343. })(BABYLON || (BABYLON = {}));
  54344. //# sourceMappingURL=babylon.analyser.js.map
  54345. var BABYLON;
  54346. (function (BABYLON) {
  54347. var CubeTexture = /** @class */ (function (_super) {
  54348. __extends(CubeTexture, _super);
  54349. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54350. if (extensions === void 0) { extensions = null; }
  54351. if (noMipmap === void 0) { noMipmap = false; }
  54352. if (files === void 0) { files = null; }
  54353. if (onLoad === void 0) { onLoad = null; }
  54354. if (onError === void 0) { onError = null; }
  54355. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54356. if (prefiltered === void 0) { prefiltered = false; }
  54357. if (forcedExtension === void 0) { forcedExtension = null; }
  54358. var _this = _super.call(this, scene) || this;
  54359. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54360. _this.name = rootUrl;
  54361. _this.url = rootUrl;
  54362. _this._noMipmap = noMipmap;
  54363. _this.hasAlpha = false;
  54364. _this._format = format;
  54365. _this._prefiltered = prefiltered;
  54366. _this.isCube = true;
  54367. _this._textureMatrix = BABYLON.Matrix.Identity();
  54368. if (prefiltered) {
  54369. _this.gammaSpace = false;
  54370. }
  54371. if (!rootUrl && !files) {
  54372. return _this;
  54373. }
  54374. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54375. var lastDot = rootUrl.lastIndexOf(".");
  54376. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54377. var isDDS = (extension === ".dds");
  54378. if (!files) {
  54379. if (!isDDS && !extensions) {
  54380. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54381. }
  54382. files = [];
  54383. if (extensions) {
  54384. for (var index = 0; index < extensions.length; index++) {
  54385. files.push(rootUrl + extensions[index]);
  54386. }
  54387. }
  54388. }
  54389. _this._files = files;
  54390. if (!_this._texture) {
  54391. if (!scene.useDelayedTextureLoading) {
  54392. if (prefiltered) {
  54393. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54394. }
  54395. else {
  54396. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54397. }
  54398. }
  54399. else {
  54400. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54401. }
  54402. }
  54403. else if (onLoad) {
  54404. if (_this._texture.isReady) {
  54405. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54406. }
  54407. else {
  54408. _this._texture.onLoadedObservable.add(onLoad);
  54409. }
  54410. }
  54411. return _this;
  54412. }
  54413. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54414. return new CubeTexture("", scene, null, noMipmap, files);
  54415. };
  54416. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54417. if (forcedExtension === void 0) { forcedExtension = null; }
  54418. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54419. };
  54420. // Methods
  54421. CubeTexture.prototype.delayLoad = function () {
  54422. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54423. return;
  54424. }
  54425. var scene = this.getScene();
  54426. if (!scene) {
  54427. return;
  54428. }
  54429. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54430. this._texture = this._getFromCache(this.url, this._noMipmap);
  54431. if (!this._texture) {
  54432. if (this._prefiltered) {
  54433. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54434. }
  54435. else {
  54436. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54437. }
  54438. }
  54439. };
  54440. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54441. return this._textureMatrix;
  54442. };
  54443. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54444. this._textureMatrix = value;
  54445. };
  54446. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54447. var texture = BABYLON.SerializationHelper.Parse(function () {
  54448. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54449. }, parsedTexture, scene);
  54450. // Animations
  54451. if (parsedTexture.animations) {
  54452. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54453. var parsedAnimation = parsedTexture.animations[animationIndex];
  54454. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54455. }
  54456. }
  54457. return texture;
  54458. };
  54459. CubeTexture.prototype.clone = function () {
  54460. var _this = this;
  54461. return BABYLON.SerializationHelper.Clone(function () {
  54462. var scene = _this.getScene();
  54463. if (!scene) {
  54464. return _this;
  54465. }
  54466. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54467. }, this);
  54468. };
  54469. return CubeTexture;
  54470. }(BABYLON.BaseTexture));
  54471. BABYLON.CubeTexture = CubeTexture;
  54472. })(BABYLON || (BABYLON = {}));
  54473. //# sourceMappingURL=babylon.cubeTexture.js.map
  54474. var BABYLON;
  54475. (function (BABYLON) {
  54476. var RenderTargetTexture = /** @class */ (function (_super) {
  54477. __extends(RenderTargetTexture, _super);
  54478. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54479. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54480. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54481. if (isCube === void 0) { isCube = false; }
  54482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54483. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54484. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54485. if (isMulti === void 0) { isMulti = false; }
  54486. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54487. _this.isCube = isCube;
  54488. /**
  54489. * Use this list to define the list of mesh you want to render.
  54490. */
  54491. _this.renderList = new Array();
  54492. _this.renderParticles = true;
  54493. _this.renderSprites = false;
  54494. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54495. _this.ignoreCameraViewport = false;
  54496. // Events
  54497. /**
  54498. * An event triggered when the texture is unbind.
  54499. * @type {BABYLON.Observable}
  54500. */
  54501. _this.onBeforeBindObservable = new BABYLON.Observable();
  54502. /**
  54503. * An event triggered when the texture is unbind.
  54504. * @type {BABYLON.Observable}
  54505. */
  54506. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54507. /**
  54508. * An event triggered before rendering the texture
  54509. * @type {BABYLON.Observable}
  54510. */
  54511. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54512. /**
  54513. * An event triggered after rendering the texture
  54514. * @type {BABYLON.Observable}
  54515. */
  54516. _this.onAfterRenderObservable = new BABYLON.Observable();
  54517. /**
  54518. * An event triggered after the texture clear
  54519. * @type {BABYLON.Observable}
  54520. */
  54521. _this.onClearObservable = new BABYLON.Observable();
  54522. _this._currentRefreshId = -1;
  54523. _this._refreshRate = 1;
  54524. _this._samples = 1;
  54525. scene = _this.getScene();
  54526. if (!scene) {
  54527. return _this;
  54528. }
  54529. _this._engine = scene.getEngine();
  54530. _this.name = name;
  54531. _this.isRenderTarget = true;
  54532. _this._initialSizeParameter = size;
  54533. _this._processSizeParameter(size);
  54534. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54535. });
  54536. _this._generateMipMaps = generateMipMaps ? true : false;
  54537. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54538. // Rendering groups
  54539. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54540. if (isMulti) {
  54541. return _this;
  54542. }
  54543. _this._renderTargetOptions = {
  54544. generateMipMaps: generateMipMaps,
  54545. type: type,
  54546. samplingMode: samplingMode,
  54547. generateDepthBuffer: generateDepthBuffer,
  54548. generateStencilBuffer: generateStencilBuffer
  54549. };
  54550. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54551. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54552. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54553. }
  54554. if (isCube) {
  54555. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54556. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54557. _this._textureMatrix = BABYLON.Matrix.Identity();
  54558. }
  54559. else {
  54560. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54561. }
  54562. return _this;
  54563. }
  54564. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54565. get: function () {
  54566. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54567. },
  54568. enumerable: true,
  54569. configurable: true
  54570. });
  54571. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54572. get: function () {
  54573. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54574. },
  54575. enumerable: true,
  54576. configurable: true
  54577. });
  54578. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54579. get: function () {
  54580. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54581. },
  54582. enumerable: true,
  54583. configurable: true
  54584. });
  54585. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54586. set: function (callback) {
  54587. if (this._onAfterUnbindObserver) {
  54588. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54589. }
  54590. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54591. },
  54592. enumerable: true,
  54593. configurable: true
  54594. });
  54595. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54596. set: function (callback) {
  54597. if (this._onBeforeRenderObserver) {
  54598. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54599. }
  54600. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54601. },
  54602. enumerable: true,
  54603. configurable: true
  54604. });
  54605. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54606. set: function (callback) {
  54607. if (this._onAfterRenderObserver) {
  54608. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54609. }
  54610. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54611. },
  54612. enumerable: true,
  54613. configurable: true
  54614. });
  54615. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54616. set: function (callback) {
  54617. if (this._onClearObserver) {
  54618. this.onClearObservable.remove(this._onClearObserver);
  54619. }
  54620. this._onClearObserver = this.onClearObservable.add(callback);
  54621. },
  54622. enumerable: true,
  54623. configurable: true
  54624. });
  54625. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54626. get: function () {
  54627. return this._renderTargetOptions;
  54628. },
  54629. enumerable: true,
  54630. configurable: true
  54631. });
  54632. RenderTargetTexture.prototype._onRatioRescale = function () {
  54633. if (this._sizeRatio) {
  54634. this.resize(this._initialSizeParameter);
  54635. }
  54636. };
  54637. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54638. if (size.ratio) {
  54639. this._sizeRatio = size.ratio;
  54640. this._size = {
  54641. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54642. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54643. };
  54644. }
  54645. else {
  54646. this._size = size;
  54647. }
  54648. };
  54649. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54650. get: function () {
  54651. return this._samples;
  54652. },
  54653. set: function (value) {
  54654. if (this._samples === value) {
  54655. return;
  54656. }
  54657. var scene = this.getScene();
  54658. if (!scene) {
  54659. return;
  54660. }
  54661. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54662. },
  54663. enumerable: true,
  54664. configurable: true
  54665. });
  54666. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54667. this._currentRefreshId = -1;
  54668. };
  54669. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54670. get: function () {
  54671. return this._refreshRate;
  54672. },
  54673. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54674. set: function (value) {
  54675. this._refreshRate = value;
  54676. this.resetRefreshCounter();
  54677. },
  54678. enumerable: true,
  54679. configurable: true
  54680. });
  54681. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54682. if (!this._postProcessManager) {
  54683. var scene = this.getScene();
  54684. if (!scene) {
  54685. return;
  54686. }
  54687. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54688. this._postProcesses = new Array();
  54689. }
  54690. this._postProcesses.push(postProcess);
  54691. this._postProcesses[0].autoClear = false;
  54692. };
  54693. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54694. if (!this._postProcesses) {
  54695. return;
  54696. }
  54697. if (dispose) {
  54698. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54699. var postProcess = _a[_i];
  54700. postProcess.dispose();
  54701. }
  54702. }
  54703. this._postProcesses = [];
  54704. };
  54705. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54706. if (!this._postProcesses) {
  54707. return;
  54708. }
  54709. var index = this._postProcesses.indexOf(postProcess);
  54710. if (index === -1) {
  54711. return;
  54712. }
  54713. this._postProcesses.splice(index, 1);
  54714. if (this._postProcesses.length > 0) {
  54715. this._postProcesses[0].autoClear = false;
  54716. }
  54717. };
  54718. RenderTargetTexture.prototype._shouldRender = function () {
  54719. if (this._currentRefreshId === -1) {
  54720. this._currentRefreshId = 1;
  54721. return true;
  54722. }
  54723. if (this.refreshRate === this._currentRefreshId) {
  54724. this._currentRefreshId = 1;
  54725. return true;
  54726. }
  54727. this._currentRefreshId++;
  54728. return false;
  54729. };
  54730. RenderTargetTexture.prototype.getRenderSize = function () {
  54731. if (this._size.width) {
  54732. return this._size.width;
  54733. }
  54734. return this._size;
  54735. };
  54736. RenderTargetTexture.prototype.getRenderWidth = function () {
  54737. if (this._size.width) {
  54738. return this._size.width;
  54739. }
  54740. return this._size;
  54741. };
  54742. RenderTargetTexture.prototype.getRenderHeight = function () {
  54743. if (this._size.width) {
  54744. return this._size.height;
  54745. }
  54746. return this._size;
  54747. };
  54748. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54749. get: function () {
  54750. return true;
  54751. },
  54752. enumerable: true,
  54753. configurable: true
  54754. });
  54755. RenderTargetTexture.prototype.scale = function (ratio) {
  54756. var newSize = this.getRenderSize() * ratio;
  54757. this.resize(newSize);
  54758. };
  54759. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54760. if (this.isCube) {
  54761. return this._textureMatrix;
  54762. }
  54763. return _super.prototype.getReflectionTextureMatrix.call(this);
  54764. };
  54765. RenderTargetTexture.prototype.resize = function (size) {
  54766. this.releaseInternalTexture();
  54767. var scene = this.getScene();
  54768. if (!scene) {
  54769. return;
  54770. }
  54771. this._processSizeParameter(size);
  54772. if (this.isCube) {
  54773. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54774. }
  54775. else {
  54776. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54777. }
  54778. };
  54779. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54780. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54781. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54782. var scene = this.getScene();
  54783. if (!scene) {
  54784. return;
  54785. }
  54786. var engine = scene.getEngine();
  54787. if (this.useCameraPostProcesses !== undefined) {
  54788. useCameraPostProcess = this.useCameraPostProcesses;
  54789. }
  54790. if (this._waitingRenderList) {
  54791. this.renderList = [];
  54792. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54793. var id = this._waitingRenderList[index];
  54794. var mesh_1 = scene.getMeshByID(id);
  54795. if (mesh_1) {
  54796. this.renderList.push(mesh_1);
  54797. }
  54798. }
  54799. delete this._waitingRenderList;
  54800. }
  54801. // Is predicate defined?
  54802. if (this.renderListPredicate) {
  54803. if (this.renderList) {
  54804. this.renderList.splice(0); // Clear previous renderList
  54805. }
  54806. else {
  54807. this.renderList = [];
  54808. }
  54809. var scene = this.getScene();
  54810. if (!scene) {
  54811. return;
  54812. }
  54813. var sceneMeshes = scene.meshes;
  54814. for (var index = 0; index < sceneMeshes.length; index++) {
  54815. var mesh = sceneMeshes[index];
  54816. if (this.renderListPredicate(mesh)) {
  54817. this.renderList.push(mesh);
  54818. }
  54819. }
  54820. }
  54821. this.onBeforeBindObservable.notifyObservers(this);
  54822. // Set custom projection.
  54823. // Needs to be before binding to prevent changing the aspect ratio.
  54824. var camera;
  54825. if (this.activeCamera) {
  54826. camera = this.activeCamera;
  54827. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54828. if (this.activeCamera !== scene.activeCamera) {
  54829. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54830. }
  54831. }
  54832. else {
  54833. camera = scene.activeCamera;
  54834. if (camera) {
  54835. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54836. }
  54837. }
  54838. // Prepare renderingManager
  54839. this._renderingManager.reset();
  54840. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54841. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54842. var sceneRenderId = scene.getRenderId();
  54843. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54844. var mesh = currentRenderList[meshIndex];
  54845. if (mesh) {
  54846. if (!mesh.isReady()) {
  54847. // Reset _currentRefreshId
  54848. this.resetRefreshCounter();
  54849. continue;
  54850. }
  54851. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54852. var isMasked = void 0;
  54853. if (!this.renderList && camera) {
  54854. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54855. }
  54856. else {
  54857. isMasked = false;
  54858. }
  54859. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54860. mesh._activate(sceneRenderId);
  54861. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54862. var subMesh = mesh.subMeshes[subIndex];
  54863. scene._activeIndices.addCount(subMesh.indexCount, false);
  54864. this._renderingManager.dispatch(subMesh, mesh);
  54865. }
  54866. }
  54867. }
  54868. }
  54869. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54870. var particleSystem = scene.particleSystems[particleIndex];
  54871. var emitter = particleSystem.emitter;
  54872. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54873. continue;
  54874. }
  54875. if (currentRenderList.indexOf(emitter) >= 0) {
  54876. this._renderingManager.dispatchParticles(particleSystem);
  54877. }
  54878. }
  54879. if (this.isCube) {
  54880. for (var face = 0; face < 6; face++) {
  54881. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54882. scene.incrementRenderId();
  54883. scene.resetCachedMaterial();
  54884. }
  54885. }
  54886. else {
  54887. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54888. }
  54889. this.onAfterUnbindObservable.notifyObservers(this);
  54890. if (scene.activeCamera) {
  54891. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54892. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54893. }
  54894. engine.setViewport(scene.activeCamera.viewport);
  54895. }
  54896. scene.resetCachedMaterial();
  54897. };
  54898. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54899. var minimum = 128;
  54900. var x = renderDimension * scale;
  54901. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54902. // Ensure we don't exceed the render dimension (while staying POT)
  54903. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54904. };
  54905. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54906. var _this = this;
  54907. if (!this._texture) {
  54908. return;
  54909. }
  54910. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54911. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54912. });
  54913. };
  54914. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54915. var scene = this.getScene();
  54916. if (!scene) {
  54917. return;
  54918. }
  54919. var engine = scene.getEngine();
  54920. if (!this._texture) {
  54921. return;
  54922. }
  54923. // Bind
  54924. if (this._postProcessManager) {
  54925. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54926. }
  54927. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54928. if (this._texture) {
  54929. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54930. }
  54931. }
  54932. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54933. // Clear
  54934. if (this.onClearObservable.hasObservers()) {
  54935. this.onClearObservable.notifyObservers(engine);
  54936. }
  54937. else {
  54938. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54939. }
  54940. if (!this._doNotChangeAspectRatio) {
  54941. scene.updateTransformMatrix(true);
  54942. }
  54943. // Render
  54944. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54945. if (this._postProcessManager) {
  54946. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54947. }
  54948. else if (useCameraPostProcess) {
  54949. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54950. }
  54951. if (!this._doNotChangeAspectRatio) {
  54952. scene.updateTransformMatrix(true);
  54953. }
  54954. // Dump ?
  54955. if (dumpForDebug) {
  54956. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54957. }
  54958. // Unbind
  54959. if (!this.isCube || faceIndex === 5) {
  54960. if (this.isCube) {
  54961. if (faceIndex === 5) {
  54962. engine.generateMipMapsForCubemap(this._texture);
  54963. }
  54964. }
  54965. this.unbindFrameBuffer(engine, faceIndex);
  54966. }
  54967. else {
  54968. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54969. }
  54970. };
  54971. /**
  54972. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54973. * This allowed control for front to back rendering or reversly depending of the special needs.
  54974. *
  54975. * @param renderingGroupId The rendering group id corresponding to its index
  54976. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54977. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54978. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54979. */
  54980. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54981. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54982. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54983. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54984. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54985. };
  54986. /**
  54987. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54988. *
  54989. * @param renderingGroupId The rendering group id corresponding to its index
  54990. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54991. */
  54992. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54993. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54994. };
  54995. RenderTargetTexture.prototype.clone = function () {
  54996. var textureSize = this.getSize();
  54997. 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);
  54998. // Base texture
  54999. newTexture.hasAlpha = this.hasAlpha;
  55000. newTexture.level = this.level;
  55001. // RenderTarget Texture
  55002. newTexture.coordinatesMode = this.coordinatesMode;
  55003. if (this.renderList) {
  55004. newTexture.renderList = this.renderList.slice(0);
  55005. }
  55006. return newTexture;
  55007. };
  55008. RenderTargetTexture.prototype.serialize = function () {
  55009. if (!this.name) {
  55010. return null;
  55011. }
  55012. var serializationObject = _super.prototype.serialize.call(this);
  55013. serializationObject.renderTargetSize = this.getRenderSize();
  55014. serializationObject.renderList = [];
  55015. if (this.renderList) {
  55016. for (var index = 0; index < this.renderList.length; index++) {
  55017. serializationObject.renderList.push(this.renderList[index].id);
  55018. }
  55019. }
  55020. return serializationObject;
  55021. };
  55022. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  55023. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  55024. var objBuffer = this.getInternalTexture();
  55025. var scene = this.getScene();
  55026. if (objBuffer && scene) {
  55027. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  55028. }
  55029. };
  55030. RenderTargetTexture.prototype.dispose = function () {
  55031. if (this._postProcessManager) {
  55032. this._postProcessManager.dispose();
  55033. this._postProcessManager = null;
  55034. }
  55035. this.clearPostProcesses(true);
  55036. if (this._resizeObserver) {
  55037. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  55038. this._resizeObserver = null;
  55039. }
  55040. this.renderList = null;
  55041. // Remove from custom render targets
  55042. var scene = this.getScene();
  55043. if (!scene) {
  55044. return;
  55045. }
  55046. var index = scene.customRenderTargets.indexOf(this);
  55047. if (index >= 0) {
  55048. scene.customRenderTargets.splice(index, 1);
  55049. }
  55050. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  55051. var camera = _a[_i];
  55052. index = camera.customRenderTargets.indexOf(this);
  55053. if (index >= 0) {
  55054. camera.customRenderTargets.splice(index, 1);
  55055. }
  55056. }
  55057. _super.prototype.dispose.call(this);
  55058. };
  55059. RenderTargetTexture.prototype._rebuild = function () {
  55060. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55061. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55062. }
  55063. if (this._postProcessManager) {
  55064. this._postProcessManager._rebuild();
  55065. }
  55066. };
  55067. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  55068. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  55069. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  55070. return RenderTargetTexture;
  55071. }(BABYLON.Texture));
  55072. BABYLON.RenderTargetTexture = RenderTargetTexture;
  55073. })(BABYLON || (BABYLON = {}));
  55074. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  55075. var BABYLON;
  55076. (function (BABYLON) {
  55077. ;
  55078. var MultiRenderTarget = /** @class */ (function (_super) {
  55079. __extends(MultiRenderTarget, _super);
  55080. function MultiRenderTarget(name, size, count, scene, options) {
  55081. var _this = this;
  55082. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  55083. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  55084. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  55085. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  55086. _this._engine = scene.getEngine();
  55087. if (!_this.isSupported) {
  55088. _this.dispose();
  55089. return;
  55090. }
  55091. var types = [];
  55092. var samplingModes = [];
  55093. for (var i = 0; i < count; i++) {
  55094. if (options && options.types && options.types[i] !== undefined) {
  55095. types.push(options.types[i]);
  55096. }
  55097. else {
  55098. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55099. }
  55100. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  55101. samplingModes.push(options.samplingModes[i]);
  55102. }
  55103. else {
  55104. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55105. }
  55106. }
  55107. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  55108. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  55109. _this._size = size;
  55110. _this._multiRenderTargetOptions = {
  55111. samplingModes: samplingModes,
  55112. generateMipMaps: generateMipMaps,
  55113. generateDepthBuffer: generateDepthBuffer,
  55114. generateStencilBuffer: generateStencilBuffer,
  55115. generateDepthTexture: generateDepthTexture,
  55116. types: types,
  55117. textureCount: count
  55118. };
  55119. _this._createInternalTextures();
  55120. _this._createTextures();
  55121. return _this;
  55122. }
  55123. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  55124. get: function () {
  55125. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  55126. },
  55127. enumerable: true,
  55128. configurable: true
  55129. });
  55130. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  55131. get: function () {
  55132. return this._textures;
  55133. },
  55134. enumerable: true,
  55135. configurable: true
  55136. });
  55137. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  55138. get: function () {
  55139. return this._textures[this._textures.length - 1];
  55140. },
  55141. enumerable: true,
  55142. configurable: true
  55143. });
  55144. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  55145. set: function (wrap) {
  55146. if (this._textures) {
  55147. for (var i = 0; i < this._textures.length; i++) {
  55148. this._textures[i].wrapU = wrap;
  55149. }
  55150. }
  55151. },
  55152. enumerable: true,
  55153. configurable: true
  55154. });
  55155. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  55156. set: function (wrap) {
  55157. if (this._textures) {
  55158. for (var i = 0; i < this._textures.length; i++) {
  55159. this._textures[i].wrapV = wrap;
  55160. }
  55161. }
  55162. },
  55163. enumerable: true,
  55164. configurable: true
  55165. });
  55166. MultiRenderTarget.prototype._rebuild = function () {
  55167. this.releaseInternalTextures();
  55168. this._createInternalTextures();
  55169. for (var i = 0; i < this._internalTextures.length; i++) {
  55170. var texture = this._textures[i];
  55171. texture._texture = this._internalTextures[i];
  55172. }
  55173. // Keeps references to frame buffer and stencil/depth buffer
  55174. this._texture = this._internalTextures[0];
  55175. };
  55176. MultiRenderTarget.prototype._createInternalTextures = function () {
  55177. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  55178. };
  55179. MultiRenderTarget.prototype._createTextures = function () {
  55180. this._textures = [];
  55181. for (var i = 0; i < this._internalTextures.length; i++) {
  55182. var texture = new BABYLON.Texture(null, this.getScene());
  55183. texture._texture = this._internalTextures[i];
  55184. this._textures.push(texture);
  55185. }
  55186. // Keeps references to frame buffer and stencil/depth buffer
  55187. this._texture = this._internalTextures[0];
  55188. };
  55189. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  55190. get: function () {
  55191. return this._samples;
  55192. },
  55193. set: function (value) {
  55194. if (this._samples === value) {
  55195. return;
  55196. }
  55197. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  55198. },
  55199. enumerable: true,
  55200. configurable: true
  55201. });
  55202. MultiRenderTarget.prototype.resize = function (size) {
  55203. this.releaseInternalTextures();
  55204. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  55205. this._createInternalTextures();
  55206. };
  55207. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  55208. var _this = this;
  55209. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  55210. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  55211. });
  55212. };
  55213. MultiRenderTarget.prototype.dispose = function () {
  55214. this.releaseInternalTextures();
  55215. _super.prototype.dispose.call(this);
  55216. };
  55217. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  55218. if (!this._internalTextures) {
  55219. return;
  55220. }
  55221. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  55222. if (this._internalTextures[i] !== undefined) {
  55223. this._internalTextures[i].dispose();
  55224. this._internalTextures.splice(i, 1);
  55225. }
  55226. }
  55227. };
  55228. return MultiRenderTarget;
  55229. }(BABYLON.RenderTargetTexture));
  55230. BABYLON.MultiRenderTarget = MultiRenderTarget;
  55231. })(BABYLON || (BABYLON = {}));
  55232. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  55233. var BABYLON;
  55234. (function (BABYLON) {
  55235. var MirrorTexture = /** @class */ (function (_super) {
  55236. __extends(MirrorTexture, _super);
  55237. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  55238. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55240. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55241. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  55242. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  55243. _this._transformMatrix = BABYLON.Matrix.Zero();
  55244. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  55245. _this._adaptiveBlurKernel = 0;
  55246. _this._blurKernelX = 0;
  55247. _this._blurKernelY = 0;
  55248. _this._blurRatio = 1.0;
  55249. _this.ignoreCameraViewport = true;
  55250. _this.onBeforeRenderObservable.add(function () {
  55251. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55252. _this._savedViewMatrix = scene.getViewMatrix();
  55253. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55254. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55255. scene.clipPlane = _this.mirrorPlane;
  55256. scene.getEngine().cullBackFaces = false;
  55257. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55258. });
  55259. _this.onAfterRenderObservable.add(function () {
  55260. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55261. scene.getEngine().cullBackFaces = true;
  55262. scene._mirroredCameraPosition = null;
  55263. delete scene.clipPlane;
  55264. });
  55265. return _this;
  55266. }
  55267. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55268. get: function () {
  55269. return this._blurRatio;
  55270. },
  55271. set: function (value) {
  55272. if (this._blurRatio === value) {
  55273. return;
  55274. }
  55275. this._blurRatio = value;
  55276. this._preparePostProcesses();
  55277. },
  55278. enumerable: true,
  55279. configurable: true
  55280. });
  55281. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55282. set: function (value) {
  55283. this._adaptiveBlurKernel = value;
  55284. this._autoComputeBlurKernel();
  55285. },
  55286. enumerable: true,
  55287. configurable: true
  55288. });
  55289. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55290. set: function (value) {
  55291. this.blurKernelX = value;
  55292. this.blurKernelY = value;
  55293. },
  55294. enumerable: true,
  55295. configurable: true
  55296. });
  55297. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55298. get: function () {
  55299. return this._blurKernelX;
  55300. },
  55301. set: function (value) {
  55302. if (this._blurKernelX === value) {
  55303. return;
  55304. }
  55305. this._blurKernelX = value;
  55306. this._preparePostProcesses();
  55307. },
  55308. enumerable: true,
  55309. configurable: true
  55310. });
  55311. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55312. get: function () {
  55313. return this._blurKernelY;
  55314. },
  55315. set: function (value) {
  55316. if (this._blurKernelY === value) {
  55317. return;
  55318. }
  55319. this._blurKernelY = value;
  55320. this._preparePostProcesses();
  55321. },
  55322. enumerable: true,
  55323. configurable: true
  55324. });
  55325. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55326. var engine = this.getScene().getEngine();
  55327. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55328. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55329. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55330. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55331. };
  55332. MirrorTexture.prototype._onRatioRescale = function () {
  55333. if (this._sizeRatio) {
  55334. this.resize(this._initialSizeParameter);
  55335. if (!this._adaptiveBlurKernel) {
  55336. this._preparePostProcesses();
  55337. }
  55338. }
  55339. if (this._adaptiveBlurKernel) {
  55340. this._autoComputeBlurKernel();
  55341. }
  55342. };
  55343. MirrorTexture.prototype._preparePostProcesses = function () {
  55344. this.clearPostProcesses(true);
  55345. if (this._blurKernelX && this._blurKernelY) {
  55346. var engine = this.getScene().getEngine();
  55347. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55348. 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);
  55349. this._blurX.autoClear = false;
  55350. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55351. this._blurX.outputTexture = this._texture;
  55352. }
  55353. else {
  55354. this._blurX.alwaysForcePOT = true;
  55355. }
  55356. 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);
  55357. this._blurY.autoClear = false;
  55358. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55359. this.addPostProcess(this._blurX);
  55360. this.addPostProcess(this._blurY);
  55361. }
  55362. else {
  55363. if (this._blurY) {
  55364. this.removePostProcess(this._blurY);
  55365. this._blurY.dispose();
  55366. this._blurY = null;
  55367. }
  55368. if (this._blurX) {
  55369. this.removePostProcess(this._blurX);
  55370. this._blurX.dispose();
  55371. this._blurX = null;
  55372. }
  55373. }
  55374. };
  55375. MirrorTexture.prototype.clone = function () {
  55376. var scene = this.getScene();
  55377. if (!scene) {
  55378. return this;
  55379. }
  55380. var textureSize = this.getSize();
  55381. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55382. // Base texture
  55383. newTexture.hasAlpha = this.hasAlpha;
  55384. newTexture.level = this.level;
  55385. // Mirror Texture
  55386. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55387. if (this.renderList) {
  55388. newTexture.renderList = this.renderList.slice(0);
  55389. }
  55390. return newTexture;
  55391. };
  55392. MirrorTexture.prototype.serialize = function () {
  55393. if (!this.name) {
  55394. return null;
  55395. }
  55396. var serializationObject = _super.prototype.serialize.call(this);
  55397. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55398. return serializationObject;
  55399. };
  55400. return MirrorTexture;
  55401. }(BABYLON.RenderTargetTexture));
  55402. BABYLON.MirrorTexture = MirrorTexture;
  55403. })(BABYLON || (BABYLON = {}));
  55404. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55405. var BABYLON;
  55406. (function (BABYLON) {
  55407. /**
  55408. * Creates a refraction texture used by refraction channel of the standard material.
  55409. * @param name the texture name
  55410. * @param size size of the underlying texture
  55411. * @param scene root scene
  55412. */
  55413. var RefractionTexture = /** @class */ (function (_super) {
  55414. __extends(RefractionTexture, _super);
  55415. function RefractionTexture(name, size, scene, generateMipMaps) {
  55416. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55417. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55418. _this.depth = 2.0;
  55419. _this.onBeforeRenderObservable.add(function () {
  55420. scene.clipPlane = _this.refractionPlane;
  55421. });
  55422. _this.onAfterRenderObservable.add(function () {
  55423. delete scene.clipPlane;
  55424. });
  55425. return _this;
  55426. }
  55427. RefractionTexture.prototype.clone = function () {
  55428. var scene = this.getScene();
  55429. if (!scene) {
  55430. return this;
  55431. }
  55432. var textureSize = this.getSize();
  55433. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55434. // Base texture
  55435. newTexture.hasAlpha = this.hasAlpha;
  55436. newTexture.level = this.level;
  55437. // Refraction Texture
  55438. newTexture.refractionPlane = this.refractionPlane.clone();
  55439. if (this.renderList) {
  55440. newTexture.renderList = this.renderList.slice(0);
  55441. }
  55442. newTexture.depth = this.depth;
  55443. return newTexture;
  55444. };
  55445. RefractionTexture.prototype.serialize = function () {
  55446. if (!this.name) {
  55447. return null;
  55448. }
  55449. var serializationObject = _super.prototype.serialize.call(this);
  55450. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55451. serializationObject.depth = this.depth;
  55452. return serializationObject;
  55453. };
  55454. return RefractionTexture;
  55455. }(BABYLON.RenderTargetTexture));
  55456. BABYLON.RefractionTexture = RefractionTexture;
  55457. })(BABYLON || (BABYLON = {}));
  55458. //# sourceMappingURL=babylon.refractionTexture.js.map
  55459. var BABYLON;
  55460. (function (BABYLON) {
  55461. var DynamicTexture = /** @class */ (function (_super) {
  55462. __extends(DynamicTexture, _super);
  55463. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55464. if (scene === void 0) { scene = null; }
  55465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55466. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55467. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55468. _this.name = name;
  55469. _this._engine = _this.getScene().getEngine();
  55470. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55471. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55472. _this._generateMipMaps = generateMipMaps;
  55473. if (options.getContext) {
  55474. _this._canvas = options;
  55475. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55476. }
  55477. else {
  55478. _this._canvas = document.createElement("canvas");
  55479. if (options.width) {
  55480. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55481. }
  55482. else {
  55483. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55484. }
  55485. }
  55486. var textureSize = _this.getSize();
  55487. _this._canvas.width = textureSize.width;
  55488. _this._canvas.height = textureSize.height;
  55489. _this._context = _this._canvas.getContext("2d");
  55490. return _this;
  55491. }
  55492. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55493. get: function () {
  55494. return true;
  55495. },
  55496. enumerable: true,
  55497. configurable: true
  55498. });
  55499. DynamicTexture.prototype._recreate = function (textureSize) {
  55500. this._canvas.width = textureSize.width;
  55501. this._canvas.height = textureSize.height;
  55502. this.releaseInternalTexture();
  55503. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55504. };
  55505. DynamicTexture.prototype.scale = function (ratio) {
  55506. var textureSize = this.getSize();
  55507. textureSize.width *= ratio;
  55508. textureSize.height *= ratio;
  55509. this._recreate(textureSize);
  55510. };
  55511. DynamicTexture.prototype.scaleTo = function (width, height) {
  55512. var textureSize = this.getSize();
  55513. textureSize.width = width;
  55514. textureSize.height = height;
  55515. this._recreate(textureSize);
  55516. };
  55517. DynamicTexture.prototype.getContext = function () {
  55518. return this._context;
  55519. };
  55520. DynamicTexture.prototype.clear = function () {
  55521. var size = this.getSize();
  55522. this._context.fillRect(0, 0, size.width, size.height);
  55523. };
  55524. DynamicTexture.prototype.update = function (invertY) {
  55525. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55526. };
  55527. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55528. if (update === void 0) { update = true; }
  55529. var size = this.getSize();
  55530. if (clearColor) {
  55531. this._context.fillStyle = clearColor;
  55532. this._context.fillRect(0, 0, size.width, size.height);
  55533. }
  55534. this._context.font = font;
  55535. if (x === null || x === undefined) {
  55536. var textSize = this._context.measureText(text);
  55537. x = (size.width - textSize.width) / 2;
  55538. }
  55539. if (y === null || y === undefined) {
  55540. var fontSize = parseInt((font.replace(/\D/g, '')));
  55541. ;
  55542. y = (size.height / 2) + (fontSize / 3.65);
  55543. }
  55544. this._context.fillStyle = color;
  55545. this._context.fillText(text, x, y);
  55546. if (update) {
  55547. this.update(invertY);
  55548. }
  55549. };
  55550. DynamicTexture.prototype.clone = function () {
  55551. var scene = this.getScene();
  55552. if (!scene) {
  55553. return this;
  55554. }
  55555. var textureSize = this.getSize();
  55556. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55557. // Base texture
  55558. newTexture.hasAlpha = this.hasAlpha;
  55559. newTexture.level = this.level;
  55560. // Dynamic Texture
  55561. newTexture.wrapU = this.wrapU;
  55562. newTexture.wrapV = this.wrapV;
  55563. return newTexture;
  55564. };
  55565. DynamicTexture.prototype._rebuild = function () {
  55566. this.update();
  55567. };
  55568. return DynamicTexture;
  55569. }(BABYLON.Texture));
  55570. BABYLON.DynamicTexture = DynamicTexture;
  55571. })(BABYLON || (BABYLON = {}));
  55572. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55573. var BABYLON;
  55574. (function (BABYLON) {
  55575. var VideoTexture = /** @class */ (function (_super) {
  55576. __extends(VideoTexture, _super);
  55577. /**
  55578. * Creates a video texture.
  55579. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55580. * @param {string | null} name optional name, will detect from video source, if not defined
  55581. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55582. * @param {BABYLON.Scene} scene is obviously the current scene.
  55583. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55584. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55585. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55586. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55587. */
  55588. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55589. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55590. if (invertY === void 0) { invertY = false; }
  55591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55592. if (settings === void 0) { settings = {
  55593. autoPlay: true,
  55594. loop: true,
  55595. autoUpdateTexture: true,
  55596. }; }
  55597. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55598. _this._createInternalTexture = function () {
  55599. if (_this._texture != null) {
  55600. return;
  55601. }
  55602. if (!_this._engine.needPOTTextures ||
  55603. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55604. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55605. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55606. }
  55607. else {
  55608. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55609. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55610. _this._generateMipMaps = false;
  55611. }
  55612. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55613. _this._texture.isReady = true;
  55614. _this._updateInternalTexture();
  55615. };
  55616. _this.reset = function () {
  55617. if (_this._texture == null) {
  55618. return;
  55619. }
  55620. _this._texture.dispose();
  55621. _this._texture = null;
  55622. };
  55623. _this._updateInternalTexture = function (e) {
  55624. if (_this._texture == null || !_this._texture.isReady) {
  55625. return;
  55626. }
  55627. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55628. return;
  55629. }
  55630. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55631. };
  55632. _this._engine = _this.getScene().getEngine();
  55633. _this._generateMipMaps = generateMipMaps;
  55634. _this._samplingMode = samplingMode;
  55635. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55636. _this.name = name || _this._getName(src);
  55637. _this.video = _this._getVideo(src);
  55638. if (settings.autoPlay !== undefined) {
  55639. _this.video.autoplay = settings.autoPlay;
  55640. }
  55641. if (settings.loop !== undefined) {
  55642. _this.video.loop = settings.loop;
  55643. }
  55644. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55645. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55646. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55647. _this.video.addEventListener("emptied", _this.reset);
  55648. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55649. _this._createInternalTexture();
  55650. }
  55651. return _this;
  55652. }
  55653. VideoTexture.prototype._getName = function (src) {
  55654. if (src instanceof HTMLVideoElement) {
  55655. return src.currentSrc;
  55656. }
  55657. if (typeof src === "object") {
  55658. return src.toString();
  55659. }
  55660. return src;
  55661. };
  55662. ;
  55663. VideoTexture.prototype._getVideo = function (src) {
  55664. if (src instanceof HTMLVideoElement) {
  55665. return src;
  55666. }
  55667. var video = document.createElement("video");
  55668. if (typeof src === "string") {
  55669. video.src = src;
  55670. }
  55671. else {
  55672. src.forEach(function (url) {
  55673. var source = document.createElement("source");
  55674. source.src = url;
  55675. video.appendChild(source);
  55676. });
  55677. }
  55678. return video;
  55679. };
  55680. ;
  55681. /**
  55682. * Internal method to initiate `update`.
  55683. */
  55684. VideoTexture.prototype._rebuild = function () {
  55685. this.update();
  55686. };
  55687. /**
  55688. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55689. */
  55690. VideoTexture.prototype.update = function () {
  55691. if (!this.autoUpdateTexture) {
  55692. // Expecting user to call `updateTexture` manually
  55693. return;
  55694. }
  55695. this.updateTexture(true);
  55696. };
  55697. /**
  55698. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55699. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55700. */
  55701. VideoTexture.prototype.updateTexture = function (isVisible) {
  55702. if (!isVisible) {
  55703. return;
  55704. }
  55705. if (this.video.paused) {
  55706. return;
  55707. }
  55708. this._updateInternalTexture();
  55709. };
  55710. /**
  55711. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55712. * @param url New url.
  55713. */
  55714. VideoTexture.prototype.updateURL = function (url) {
  55715. this.video.src = url;
  55716. };
  55717. VideoTexture.prototype.dispose = function () {
  55718. _super.prototype.dispose.call(this);
  55719. this.video.removeEventListener("canplay", this._createInternalTexture);
  55720. this.video.removeEventListener("paused", this._updateInternalTexture);
  55721. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55722. this.video.removeEventListener("emptied", this.reset);
  55723. };
  55724. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55725. var video = document.createElement("video");
  55726. var constraintsDeviceId;
  55727. if (constraints && constraints.deviceId) {
  55728. constraintsDeviceId = {
  55729. exact: constraints.deviceId,
  55730. };
  55731. }
  55732. navigator.getUserMedia =
  55733. navigator.getUserMedia ||
  55734. navigator.webkitGetUserMedia ||
  55735. navigator.mozGetUserMedia ||
  55736. navigator.msGetUserMedia;
  55737. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55738. if (navigator.getUserMedia) {
  55739. navigator.getUserMedia({
  55740. video: {
  55741. deviceId: constraintsDeviceId,
  55742. width: {
  55743. min: (constraints && constraints.minWidth) || 256,
  55744. max: (constraints && constraints.maxWidth) || 640,
  55745. },
  55746. height: {
  55747. min: (constraints && constraints.minHeight) || 256,
  55748. max: (constraints && constraints.maxHeight) || 480,
  55749. },
  55750. },
  55751. }, function (stream) {
  55752. if (video.mozSrcObject !== undefined) {
  55753. // hack for Firefox < 19
  55754. video.mozSrcObject = stream;
  55755. }
  55756. else {
  55757. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55758. }
  55759. video.play();
  55760. if (onReady) {
  55761. onReady(new VideoTexture("video", video, scene, true, true));
  55762. }
  55763. }, function (e) {
  55764. BABYLON.Tools.Error(e.name);
  55765. });
  55766. }
  55767. };
  55768. return VideoTexture;
  55769. }(BABYLON.Texture));
  55770. BABYLON.VideoTexture = VideoTexture;
  55771. })(BABYLON || (BABYLON = {}));
  55772. //# sourceMappingURL=babylon.videoTexture.js.map
  55773. var BABYLON;
  55774. (function (BABYLON) {
  55775. var RawTexture = /** @class */ (function (_super) {
  55776. __extends(RawTexture, _super);
  55777. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55778. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55779. if (invertY === void 0) { invertY = false; }
  55780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55781. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55782. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55783. _this.format = format;
  55784. _this._engine = scene.getEngine();
  55785. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55786. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55787. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55788. return _this;
  55789. }
  55790. RawTexture.prototype.update = function (data) {
  55791. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55792. };
  55793. // Statics
  55794. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55795. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55796. if (invertY === void 0) { invertY = false; }
  55797. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55798. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55799. };
  55800. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55801. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55802. if (invertY === void 0) { invertY = false; }
  55803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55804. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55805. };
  55806. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55807. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55808. if (invertY === void 0) { invertY = false; }
  55809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55810. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55811. };
  55812. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55813. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55814. if (invertY === void 0) { invertY = false; }
  55815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55816. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55817. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55818. };
  55819. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55820. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55821. if (invertY === void 0) { invertY = false; }
  55822. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55823. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55824. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55825. };
  55826. return RawTexture;
  55827. }(BABYLON.Texture));
  55828. BABYLON.RawTexture = RawTexture;
  55829. })(BABYLON || (BABYLON = {}));
  55830. //# sourceMappingURL=babylon.rawTexture.js.map
  55831. var BABYLON;
  55832. (function (BABYLON) {
  55833. /**
  55834. * PostProcess can be used to apply a shader to a texture after it has been rendered
  55835. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  55836. */
  55837. var PostProcess = /** @class */ (function () {
  55838. /**
  55839. * Creates a new instance of @see PostProcess
  55840. * @param name The name of the PostProcess.
  55841. * @param fragmentUrl The url of the fragment shader to be used.
  55842. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  55843. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  55844. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  55845. * @param camera The camera to apply the render pass to.
  55846. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  55847. * @param engine The engine which the post process will be applied. (default: current engine)
  55848. * @param reusable If the post process can be reused on the same frame. (default: false)
  55849. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  55850. * @param textureType Type of textures used when performing the post process. (default: 0)
  55851. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  55852. * @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
  55853. * @param blockCompilation If the shader should be compiled imediatly. (default: false)
  55854. */
  55855. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55857. if (defines === void 0) { defines = null; }
  55858. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55859. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55860. if (blockCompilation === void 0) { blockCompilation = false; }
  55861. this.name = name;
  55862. /**
  55863. * Width of the texture to apply the post process on
  55864. */
  55865. this.width = -1;
  55866. /**
  55867. * Height of the texture to apply the post process on
  55868. */
  55869. this.height = -1;
  55870. /**
  55871. * If the buffer needs to be cleared before applying the post process. (default: true)
  55872. * Should be set to false if shader will overwrite all previous pixels.
  55873. */
  55874. this.autoClear = true;
  55875. /**
  55876. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  55877. */
  55878. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55879. /**
  55880. * Animations to be used for the post processing
  55881. */
  55882. this.animations = new Array();
  55883. /**
  55884. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55885. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  55886. */
  55887. this.enablePixelPerfectMode = false;
  55888. /**
  55889. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  55890. */
  55891. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55892. /**
  55893. * Force textures to be a power of two (default: false)
  55894. */
  55895. this.alwaysForcePOT = false;
  55896. /**
  55897. * Number of sample textures (default: 1)
  55898. */
  55899. this.samples = 1;
  55900. /**
  55901. * Modify the scale of the post process to be the same as the viewport (default: false)
  55902. */
  55903. this.adaptScaleToCurrentViewport = false;
  55904. this._reusable = false;
  55905. /**
  55906. * Smart array of input and output textures for the post process.
  55907. */
  55908. this._textures = new BABYLON.SmartArray(2);
  55909. /**
  55910. * The index in _textures that corresponds to the output texture.
  55911. */
  55912. this._currentRenderTextureInd = 0;
  55913. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55914. this._texelSize = BABYLON.Vector2.Zero();
  55915. // Events
  55916. /**
  55917. * An event triggered when the postprocess is activated.
  55918. * @type {BABYLON.Observable}
  55919. */
  55920. this.onActivateObservable = new BABYLON.Observable();
  55921. /**
  55922. * An event triggered when the postprocess changes its size.
  55923. * @type {BABYLON.Observable}
  55924. */
  55925. this.onSizeChangedObservable = new BABYLON.Observable();
  55926. /**
  55927. * An event triggered when the postprocess applies its effect.
  55928. * @type {BABYLON.Observable}
  55929. */
  55930. this.onApplyObservable = new BABYLON.Observable();
  55931. /**
  55932. * An event triggered before rendering the postprocess
  55933. * @type {BABYLON.Observable}
  55934. */
  55935. this.onBeforeRenderObservable = new BABYLON.Observable();
  55936. /**
  55937. * An event triggered after rendering the postprocess
  55938. * @type {BABYLON.Observable}
  55939. */
  55940. this.onAfterRenderObservable = new BABYLON.Observable();
  55941. if (camera != null) {
  55942. this._camera = camera;
  55943. this._scene = camera.getScene();
  55944. camera.attachPostProcess(this);
  55945. this._engine = this._scene.getEngine();
  55946. this._scene.postProcesses.push(this);
  55947. }
  55948. else if (engine) {
  55949. this._engine = engine;
  55950. this._engine.postProcesses.push(this);
  55951. }
  55952. this._options = options;
  55953. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55954. this._reusable = reusable || false;
  55955. this._textureType = textureType;
  55956. this._samplers = samplers || [];
  55957. this._samplers.push("textureSampler");
  55958. this._fragmentUrl = fragmentUrl;
  55959. this._vertexUrl = vertexUrl;
  55960. this._parameters = parameters || [];
  55961. this._parameters.push("scale");
  55962. this._indexParameters = indexParameters;
  55963. if (!blockCompilation) {
  55964. this.updateEffect(defines);
  55965. }
  55966. }
  55967. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55968. /**
  55969. * A function that is added to the onActivateObservable
  55970. */
  55971. set: function (callback) {
  55972. if (this._onActivateObserver) {
  55973. this.onActivateObservable.remove(this._onActivateObserver);
  55974. }
  55975. if (callback) {
  55976. this._onActivateObserver = this.onActivateObservable.add(callback);
  55977. }
  55978. },
  55979. enumerable: true,
  55980. configurable: true
  55981. });
  55982. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55983. /**
  55984. * A function that is added to the onSizeChangedObservable
  55985. */
  55986. set: function (callback) {
  55987. if (this._onSizeChangedObserver) {
  55988. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55989. }
  55990. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55991. },
  55992. enumerable: true,
  55993. configurable: true
  55994. });
  55995. Object.defineProperty(PostProcess.prototype, "onApply", {
  55996. /**
  55997. * A function that is added to the onApplyObservable
  55998. */
  55999. set: function (callback) {
  56000. if (this._onApplyObserver) {
  56001. this.onApplyObservable.remove(this._onApplyObserver);
  56002. }
  56003. this._onApplyObserver = this.onApplyObservable.add(callback);
  56004. },
  56005. enumerable: true,
  56006. configurable: true
  56007. });
  56008. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  56009. /**
  56010. * A function that is added to the onBeforeRenderObservable
  56011. */
  56012. set: function (callback) {
  56013. if (this._onBeforeRenderObserver) {
  56014. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56015. }
  56016. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56017. },
  56018. enumerable: true,
  56019. configurable: true
  56020. });
  56021. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  56022. /**
  56023. * A function that is added to the onAfterRenderObservable
  56024. */
  56025. set: function (callback) {
  56026. if (this._onAfterRenderObserver) {
  56027. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56028. }
  56029. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56030. },
  56031. enumerable: true,
  56032. configurable: true
  56033. });
  56034. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  56035. /**
  56036. * The resulting output of the post process.
  56037. */
  56038. get: function () {
  56039. return this._textures.data[this._currentRenderTextureInd];
  56040. },
  56041. set: function (value) {
  56042. this._forcedOutputTexture = value;
  56043. },
  56044. enumerable: true,
  56045. configurable: true
  56046. });
  56047. /**
  56048. * Gets the camera which post process is applied to.
  56049. * @returns The camera the post process is applied to.
  56050. */
  56051. PostProcess.prototype.getCamera = function () {
  56052. return this._camera;
  56053. };
  56054. Object.defineProperty(PostProcess.prototype, "texelSize", {
  56055. /**
  56056. * Gets the texel size of the postprocess.
  56057. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  56058. */
  56059. get: function () {
  56060. if (this._shareOutputWithPostProcess) {
  56061. return this._shareOutputWithPostProcess.texelSize;
  56062. }
  56063. if (this._forcedOutputTexture) {
  56064. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  56065. }
  56066. return this._texelSize;
  56067. },
  56068. enumerable: true,
  56069. configurable: true
  56070. });
  56071. /**
  56072. * Gets the engine which this post process belongs to.
  56073. * @returns The engine the post process was enabled with.
  56074. */
  56075. PostProcess.prototype.getEngine = function () {
  56076. return this._engine;
  56077. };
  56078. /**
  56079. * The effect that is created when initializing the post process.
  56080. * @returns The created effect corrisponding the the postprocess.
  56081. */
  56082. PostProcess.prototype.getEffect = function () {
  56083. return this._effect;
  56084. };
  56085. /**
  56086. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  56087. * @param postProcess The post process to share the output with.
  56088. * @returns This post process.
  56089. */
  56090. PostProcess.prototype.shareOutputWith = function (postProcess) {
  56091. this._disposeTextures();
  56092. this._shareOutputWithPostProcess = postProcess;
  56093. return this;
  56094. };
  56095. /**
  56096. * Updates the effect with the current post process compile time values and recompiles the shader.
  56097. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  56098. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  56099. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  56100. * @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
  56101. * @param onCompiled Called when the shader has been compiled.
  56102. * @param onError Called if there is an error when compiling a shader.
  56103. */
  56104. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  56105. if (defines === void 0) { defines = null; }
  56106. if (uniforms === void 0) { uniforms = null; }
  56107. if (samplers === void 0) { samplers = null; }
  56108. 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);
  56109. };
  56110. /**
  56111. * The post process is reusable if it can be used multiple times within one frame.
  56112. * @returns If the post process is reusable
  56113. */
  56114. PostProcess.prototype.isReusable = function () {
  56115. return this._reusable;
  56116. };
  56117. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  56118. PostProcess.prototype.markTextureDirty = function () {
  56119. this.width = -1;
  56120. };
  56121. /**
  56122. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  56123. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  56124. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  56125. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  56126. */
  56127. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  56128. var _this = this;
  56129. if (sourceTexture === void 0) { sourceTexture = null; }
  56130. camera = camera || this._camera;
  56131. var scene = camera.getScene();
  56132. var engine = scene.getEngine();
  56133. var maxSize = engine.getCaps().maxTextureSize;
  56134. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  56135. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  56136. var desiredWidth = (this._options.width || requiredWidth);
  56137. var desiredHeight = this._options.height || requiredHeight;
  56138. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  56139. if (this.adaptScaleToCurrentViewport) {
  56140. var currentViewport = engine.currentViewport;
  56141. if (currentViewport) {
  56142. desiredWidth *= currentViewport.width;
  56143. desiredHeight *= currentViewport.height;
  56144. }
  56145. }
  56146. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  56147. if (!this._options.width) {
  56148. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  56149. }
  56150. if (!this._options.height) {
  56151. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  56152. }
  56153. }
  56154. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  56155. if (this._textures.length > 0) {
  56156. for (var i = 0; i < this._textures.length; i++) {
  56157. this._engine._releaseTexture(this._textures.data[i]);
  56158. }
  56159. this._textures.reset();
  56160. }
  56161. this.width = desiredWidth;
  56162. this.height = desiredHeight;
  56163. var textureSize = { width: this.width, height: this.height };
  56164. var textureOptions = {
  56165. generateMipMaps: false,
  56166. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  56167. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  56168. samplingMode: this.renderTargetSamplingMode,
  56169. type: this._textureType
  56170. };
  56171. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56172. if (this._reusable) {
  56173. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56174. }
  56175. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  56176. this.onSizeChangedObservable.notifyObservers(this);
  56177. }
  56178. this._textures.forEach(function (texture) {
  56179. if (texture.samples !== _this.samples) {
  56180. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  56181. }
  56182. });
  56183. }
  56184. var target;
  56185. if (this._shareOutputWithPostProcess) {
  56186. target = this._shareOutputWithPostProcess.outputTexture;
  56187. }
  56188. else if (this._forcedOutputTexture) {
  56189. target = this._forcedOutputTexture;
  56190. this.width = this._forcedOutputTexture.width;
  56191. this.height = this._forcedOutputTexture.height;
  56192. }
  56193. else {
  56194. target = this.outputTexture;
  56195. }
  56196. if (this.enablePixelPerfectMode) {
  56197. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  56198. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  56199. }
  56200. else {
  56201. this._scaleRatio.copyFromFloats(1, 1);
  56202. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  56203. }
  56204. this.onActivateObservable.notifyObservers(camera);
  56205. // Clear
  56206. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  56207. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  56208. }
  56209. if (this._reusable) {
  56210. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  56211. }
  56212. };
  56213. Object.defineProperty(PostProcess.prototype, "isSupported", {
  56214. /**
  56215. * If the post process is supported.
  56216. */
  56217. get: function () {
  56218. return this._effect.isSupported;
  56219. },
  56220. enumerable: true,
  56221. configurable: true
  56222. });
  56223. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  56224. /**
  56225. * The aspect ratio of the output texture.
  56226. */
  56227. get: function () {
  56228. if (this._shareOutputWithPostProcess) {
  56229. return this._shareOutputWithPostProcess.aspectRatio;
  56230. }
  56231. if (this._forcedOutputTexture) {
  56232. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  56233. }
  56234. return this.width / this.height;
  56235. },
  56236. enumerable: true,
  56237. configurable: true
  56238. });
  56239. /**
  56240. * Get a value indicating if the post-process is ready to be used
  56241. * @returns true if the post-process is ready (shader is compiled)
  56242. */
  56243. PostProcess.prototype.isReady = function () {
  56244. return this._effect && this._effect.isReady();
  56245. };
  56246. /**
  56247. * Binds all textures and uniforms to the shader, this will be run on every pass.
  56248. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  56249. */
  56250. PostProcess.prototype.apply = function () {
  56251. // Check
  56252. if (!this._effect || !this._effect.isReady())
  56253. return null;
  56254. // States
  56255. this._engine.enableEffect(this._effect);
  56256. this._engine.setState(false);
  56257. this._engine.setDepthBuffer(false);
  56258. this._engine.setDepthWrite(false);
  56259. // Alpha
  56260. this._engine.setAlphaMode(this.alphaMode);
  56261. if (this.alphaConstants) {
  56262. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  56263. }
  56264. // Texture
  56265. var source;
  56266. if (this._shareOutputWithPostProcess) {
  56267. source = this._shareOutputWithPostProcess.outputTexture;
  56268. }
  56269. else if (this._forcedOutputTexture) {
  56270. source = this._forcedOutputTexture;
  56271. }
  56272. else {
  56273. source = this.outputTexture;
  56274. }
  56275. this._effect._bindTexture("textureSampler", source);
  56276. // Parameters
  56277. this._effect.setVector2("scale", this._scaleRatio);
  56278. this.onApplyObservable.notifyObservers(this._effect);
  56279. return this._effect;
  56280. };
  56281. PostProcess.prototype._disposeTextures = function () {
  56282. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  56283. return;
  56284. }
  56285. if (this._textures.length > 0) {
  56286. for (var i = 0; i < this._textures.length; i++) {
  56287. this._engine._releaseTexture(this._textures.data[i]);
  56288. }
  56289. }
  56290. this._textures.dispose();
  56291. };
  56292. /**
  56293. * Disposes the post process.
  56294. * @param camera The camera to dispose the post process on.
  56295. */
  56296. PostProcess.prototype.dispose = function (camera) {
  56297. camera = camera || this._camera;
  56298. this._disposeTextures();
  56299. if (this._scene) {
  56300. var index_1 = this._scene.postProcesses.indexOf(this);
  56301. if (index_1 !== -1) {
  56302. this._scene.postProcesses.splice(index_1, 1);
  56303. }
  56304. }
  56305. else {
  56306. var index_2 = this._engine.postProcesses.indexOf(this);
  56307. if (index_2 !== -1) {
  56308. this._engine.postProcesses.splice(index_2, 1);
  56309. }
  56310. }
  56311. if (!camera) {
  56312. return;
  56313. }
  56314. camera.detachPostProcess(this);
  56315. var index = camera._postProcesses.indexOf(this);
  56316. if (index === 0 && camera._postProcesses.length > 0) {
  56317. this._camera._postProcesses[0].markTextureDirty();
  56318. }
  56319. this.onActivateObservable.clear();
  56320. this.onAfterRenderObservable.clear();
  56321. this.onApplyObservable.clear();
  56322. this.onBeforeRenderObservable.clear();
  56323. this.onSizeChangedObservable.clear();
  56324. };
  56325. return PostProcess;
  56326. }());
  56327. BABYLON.PostProcess = PostProcess;
  56328. })(BABYLON || (BABYLON = {}));
  56329. //# sourceMappingURL=babylon.postProcess.js.map
  56330. var BABYLON;
  56331. (function (BABYLON) {
  56332. var PassPostProcess = /** @class */ (function (_super) {
  56333. __extends(PassPostProcess, _super);
  56334. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56335. if (camera === void 0) { camera = null; }
  56336. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56337. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  56338. }
  56339. return PassPostProcess;
  56340. }(BABYLON.PostProcess));
  56341. BABYLON.PassPostProcess = PassPostProcess;
  56342. })(BABYLON || (BABYLON = {}));
  56343. //# sourceMappingURL=babylon.passPostProcess.js.map
  56344. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56345. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56346. s = arguments[i];
  56347. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56348. t[p] = s[p];
  56349. }
  56350. return t;
  56351. };
  56352. var BABYLON;
  56353. (function (BABYLON) {
  56354. /**
  56355. * Default implementation of @see IShadowGenerator.
  56356. * This is the main object responsible of generating shadows in the framework.
  56357. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  56358. */
  56359. var ShadowGenerator = /** @class */ (function () {
  56360. /**
  56361. * Creates a ShadowGenerator object.
  56362. * A ShadowGenerator is the required tool to use the shadows.
  56363. * Each light casting shadows needs to use its own ShadowGenerator.
  56364. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  56365. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  56366. * @param light The light object generating the shadows.
  56367. * @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.
  56368. */
  56369. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  56370. this._bias = 0.00005;
  56371. this._blurBoxOffset = 1;
  56372. this._blurScale = 2;
  56373. this._blurKernel = 1;
  56374. this._useKernelBlur = false;
  56375. this._filter = ShadowGenerator.FILTER_NONE;
  56376. this._darkness = 0;
  56377. this._transparencyShadow = false;
  56378. /**
  56379. * Controls the extent to which the shadows fade out at the edge of the frustum
  56380. * Used only by directionals and spots
  56381. */
  56382. this.frustumEdgeFalloff = 0;
  56383. /**
  56384. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56385. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56386. * It might on the other hand introduce peter panning.
  56387. */
  56388. this.forceBackFacesOnly = false;
  56389. this._lightDirection = BABYLON.Vector3.Zero();
  56390. this._viewMatrix = BABYLON.Matrix.Zero();
  56391. this._projectionMatrix = BABYLON.Matrix.Zero();
  56392. this._transformMatrix = BABYLON.Matrix.Zero();
  56393. this._currentFaceIndex = 0;
  56394. this._currentFaceIndexCache = 0;
  56395. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56396. this._mapSize = mapSize;
  56397. this._light = light;
  56398. this._scene = light.getScene();
  56399. light._shadowGenerator = this;
  56400. // Texture type fallback from float to int if not supported.
  56401. var caps = this._scene.getEngine().getCaps();
  56402. if (!useFullFloatFirst) {
  56403. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56404. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56405. }
  56406. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56407. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56408. }
  56409. else {
  56410. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56411. }
  56412. }
  56413. else {
  56414. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56415. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56416. }
  56417. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56418. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56419. }
  56420. else {
  56421. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56422. }
  56423. }
  56424. this._initializeGenerator();
  56425. }
  56426. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56427. /**
  56428. * Shadow generator mode None: no filtering applied.
  56429. */
  56430. get: function () {
  56431. return ShadowGenerator._FILTER_NONE;
  56432. },
  56433. enumerable: true,
  56434. configurable: true
  56435. });
  56436. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56437. /**
  56438. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56439. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56440. */
  56441. get: function () {
  56442. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56443. },
  56444. enumerable: true,
  56445. configurable: true
  56446. });
  56447. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56448. /**
  56449. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56450. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56451. */
  56452. get: function () {
  56453. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56454. },
  56455. enumerable: true,
  56456. configurable: true
  56457. });
  56458. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56459. /**
  56460. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56461. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56462. */
  56463. get: function () {
  56464. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56465. },
  56466. enumerable: true,
  56467. configurable: true
  56468. });
  56469. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56470. /**
  56471. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56472. * edge artifacts on steep falloff.
  56473. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56474. */
  56475. get: function () {
  56476. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56477. },
  56478. enumerable: true,
  56479. configurable: true
  56480. });
  56481. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56482. /**
  56483. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56484. * edge artifacts on steep falloff.
  56485. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56486. */
  56487. get: function () {
  56488. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56494. /**
  56495. * Gets the bias: offset applied on the depth preventing acnea.
  56496. */
  56497. get: function () {
  56498. return this._bias;
  56499. },
  56500. /**
  56501. * Sets the bias: offset applied on the depth preventing acnea.
  56502. */
  56503. set: function (bias) {
  56504. this._bias = bias;
  56505. },
  56506. enumerable: true,
  56507. configurable: true
  56508. });
  56509. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56510. /**
  56511. * Gets the blur box offset: offset applied during the blur pass.
  56512. * Only usefull if useKernelBlur = false
  56513. */
  56514. get: function () {
  56515. return this._blurBoxOffset;
  56516. },
  56517. /**
  56518. * Sets the blur box offset: offset applied during the blur pass.
  56519. * Only usefull if useKernelBlur = false
  56520. */
  56521. set: function (value) {
  56522. if (this._blurBoxOffset === value) {
  56523. return;
  56524. }
  56525. this._blurBoxOffset = value;
  56526. this._disposeBlurPostProcesses();
  56527. },
  56528. enumerable: true,
  56529. configurable: true
  56530. });
  56531. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56532. /**
  56533. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56534. * 2 means half of the size.
  56535. */
  56536. get: function () {
  56537. return this._blurScale;
  56538. },
  56539. /**
  56540. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56541. * 2 means half of the size.
  56542. */
  56543. set: function (value) {
  56544. if (this._blurScale === value) {
  56545. return;
  56546. }
  56547. this._blurScale = value;
  56548. this._disposeBlurPostProcesses();
  56549. },
  56550. enumerable: true,
  56551. configurable: true
  56552. });
  56553. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56554. /**
  56555. * Gets the blur kernel: kernel size of the blur pass.
  56556. * Only usefull if useKernelBlur = true
  56557. */
  56558. get: function () {
  56559. return this._blurKernel;
  56560. },
  56561. /**
  56562. * Sets the blur kernel: kernel size of the blur pass.
  56563. * Only usefull if useKernelBlur = true
  56564. */
  56565. set: function (value) {
  56566. if (this._blurKernel === value) {
  56567. return;
  56568. }
  56569. this._blurKernel = value;
  56570. this._disposeBlurPostProcesses();
  56571. },
  56572. enumerable: true,
  56573. configurable: true
  56574. });
  56575. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56576. /**
  56577. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56578. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56579. */
  56580. get: function () {
  56581. return this._useKernelBlur;
  56582. },
  56583. /**
  56584. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56585. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56586. */
  56587. set: function (value) {
  56588. if (this._useKernelBlur === value) {
  56589. return;
  56590. }
  56591. this._useKernelBlur = value;
  56592. this._disposeBlurPostProcesses();
  56593. },
  56594. enumerable: true,
  56595. configurable: true
  56596. });
  56597. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56598. /**
  56599. * Gets the depth scale used in ESM mode.
  56600. */
  56601. get: function () {
  56602. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56603. },
  56604. /**
  56605. * Sets the depth scale used in ESM mode.
  56606. * This can override the scale stored on the light.
  56607. */
  56608. set: function (value) {
  56609. this._depthScale = value;
  56610. },
  56611. enumerable: true,
  56612. configurable: true
  56613. });
  56614. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56615. /**
  56616. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56617. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56618. */
  56619. get: function () {
  56620. return this._filter;
  56621. },
  56622. /**
  56623. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56624. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56625. */
  56626. set: function (value) {
  56627. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56628. if (this._light.needCube()) {
  56629. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56630. this.useExponentialShadowMap = true;
  56631. return;
  56632. }
  56633. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56634. this.useCloseExponentialShadowMap = true;
  56635. return;
  56636. }
  56637. }
  56638. if (this._filter === value) {
  56639. return;
  56640. }
  56641. this._filter = value;
  56642. this._disposeBlurPostProcesses();
  56643. this._applyFilterValues();
  56644. this._light._markMeshesAsLightDirty();
  56645. },
  56646. enumerable: true,
  56647. configurable: true
  56648. });
  56649. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56650. /**
  56651. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56652. */
  56653. get: function () {
  56654. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56655. },
  56656. /**
  56657. * Sets the current filter to Poisson Sampling aka PCF.
  56658. */
  56659. set: function (value) {
  56660. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56661. return;
  56662. }
  56663. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56664. },
  56665. enumerable: true,
  56666. configurable: true
  56667. });
  56668. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56669. /**
  56670. * Gets if the current filter is set to VSM.
  56671. * DEPRECATED. Should use useExponentialShadowMap instead.
  56672. */
  56673. get: function () {
  56674. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56675. return this.useExponentialShadowMap;
  56676. },
  56677. /**
  56678. * Sets the current filter is to VSM.
  56679. * DEPRECATED. Should use useExponentialShadowMap instead.
  56680. */
  56681. set: function (value) {
  56682. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56683. this.useExponentialShadowMap = value;
  56684. },
  56685. enumerable: true,
  56686. configurable: true
  56687. });
  56688. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56689. /**
  56690. * Gets if the current filter is set to blurred VSM.
  56691. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56692. */
  56693. get: function () {
  56694. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56695. return this.useBlurExponentialShadowMap;
  56696. },
  56697. /**
  56698. * Sets the current filter is to blurred VSM.
  56699. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56700. */
  56701. set: function (value) {
  56702. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56703. this.useBlurExponentialShadowMap = value;
  56704. },
  56705. enumerable: true,
  56706. configurable: true
  56707. });
  56708. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56709. /**
  56710. * Gets if the current filter is set to ESM.
  56711. */
  56712. get: function () {
  56713. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56714. },
  56715. /**
  56716. * Sets the current filter is to ESM.
  56717. */
  56718. set: function (value) {
  56719. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56720. return;
  56721. }
  56722. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56723. },
  56724. enumerable: true,
  56725. configurable: true
  56726. });
  56727. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56728. /**
  56729. * Gets if the current filter is set to filtered ESM.
  56730. */
  56731. get: function () {
  56732. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56733. },
  56734. /**
  56735. * Gets if the current filter is set to filtered ESM.
  56736. */
  56737. set: function (value) {
  56738. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56739. return;
  56740. }
  56741. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56742. },
  56743. enumerable: true,
  56744. configurable: true
  56745. });
  56746. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56747. /**
  56748. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56749. * exponential to prevent steep falloff artifacts).
  56750. */
  56751. get: function () {
  56752. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56753. },
  56754. /**
  56755. * Sets the current filter to "close ESM" (using the inverse of the
  56756. * exponential to prevent steep falloff artifacts).
  56757. */
  56758. set: function (value) {
  56759. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56760. return;
  56761. }
  56762. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56763. },
  56764. enumerable: true,
  56765. configurable: true
  56766. });
  56767. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56768. /**
  56769. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56770. * exponential to prevent steep falloff artifacts).
  56771. */
  56772. get: function () {
  56773. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56774. },
  56775. /**
  56776. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56777. * exponential to prevent steep falloff artifacts).
  56778. */
  56779. set: function (value) {
  56780. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56781. return;
  56782. }
  56783. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56784. },
  56785. enumerable: true,
  56786. configurable: true
  56787. });
  56788. /**
  56789. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56790. * 0 means strongest and 1 would means no shadow.
  56791. * @returns the darkness.
  56792. */
  56793. ShadowGenerator.prototype.getDarkness = function () {
  56794. return this._darkness;
  56795. };
  56796. /**
  56797. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56798. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56799. * @returns the shadow generator allowing fluent coding.
  56800. */
  56801. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56802. if (darkness >= 1.0)
  56803. this._darkness = 1.0;
  56804. else if (darkness <= 0.0)
  56805. this._darkness = 0.0;
  56806. else
  56807. this._darkness = darkness;
  56808. return this;
  56809. };
  56810. /**
  56811. * Sets the ability to have transparent shadow (boolean).
  56812. * @param transparent True if transparent else False
  56813. * @returns the shadow generator allowing fluent coding
  56814. */
  56815. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  56816. this._transparencyShadow = transparent;
  56817. return this;
  56818. };
  56819. /**
  56820. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  56821. * @returns The render target texture if present otherwise, null
  56822. */
  56823. ShadowGenerator.prototype.getShadowMap = function () {
  56824. return this._shadowMap;
  56825. };
  56826. /**
  56827. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  56828. * @returns The render target texture if the shadow map is present otherwise, null
  56829. */
  56830. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  56831. if (this._shadowMap2) {
  56832. return this._shadowMap2;
  56833. }
  56834. return this._shadowMap;
  56835. };
  56836. /**
  56837. * Helper function to add a mesh and its descendants to the list of shadow casters.
  56838. * @param mesh Mesh to add
  56839. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56840. * @returns the Shadow Generator itself
  56841. */
  56842. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56843. if (includeDescendants === void 0) { includeDescendants = true; }
  56844. if (!this._shadowMap) {
  56845. return this;
  56846. }
  56847. if (!this._shadowMap.renderList) {
  56848. this._shadowMap.renderList = [];
  56849. }
  56850. this._shadowMap.renderList.push(mesh);
  56851. if (includeDescendants) {
  56852. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56853. }
  56854. return this;
  56855. var _a;
  56856. };
  56857. /**
  56858. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56859. * @param mesh Mesh to remove
  56860. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56861. * @returns the Shadow Generator itself
  56862. */
  56863. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56864. if (includeDescendants === void 0) { includeDescendants = true; }
  56865. if (!this._shadowMap || !this._shadowMap.renderList) {
  56866. return this;
  56867. }
  56868. var index = this._shadowMap.renderList.indexOf(mesh);
  56869. if (index !== -1) {
  56870. this._shadowMap.renderList.splice(index, 1);
  56871. }
  56872. if (includeDescendants) {
  56873. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56874. var child = _a[_i];
  56875. this.removeShadowCaster(child);
  56876. }
  56877. }
  56878. return this;
  56879. };
  56880. /**
  56881. * Returns the associated light object.
  56882. * @returns the light generating the shadow
  56883. */
  56884. ShadowGenerator.prototype.getLight = function () {
  56885. return this._light;
  56886. };
  56887. ShadowGenerator.prototype._initializeGenerator = function () {
  56888. this._light._markMeshesAsLightDirty();
  56889. this._initializeShadowMap();
  56890. };
  56891. ShadowGenerator.prototype._initializeShadowMap = function () {
  56892. var _this = this;
  56893. // Render target
  56894. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56895. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56896. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56897. this._shadowMap.anisotropicFilteringLevel = 1;
  56898. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56899. this._shadowMap.renderParticles = false;
  56900. this._shadowMap.ignoreCameraViewport = true;
  56901. // Record Face Index before render.
  56902. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56903. _this._currentFaceIndex = faceIndex;
  56904. });
  56905. // Custom render function.
  56906. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56907. // Blur if required afer render.
  56908. this._shadowMap.onAfterUnbindObservable.add(function () {
  56909. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56910. return;
  56911. }
  56912. var shadowMap = _this.getShadowMapForRendering();
  56913. if (shadowMap) {
  56914. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56915. }
  56916. });
  56917. // Clear according to the chosen filter.
  56918. this._shadowMap.onClearObservable.add(function (engine) {
  56919. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56920. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56921. }
  56922. else {
  56923. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56924. }
  56925. });
  56926. };
  56927. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56928. var _this = this;
  56929. var engine = this._scene.getEngine();
  56930. var targetSize = this._mapSize / this.blurScale;
  56931. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56932. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56933. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56934. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56935. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56936. }
  56937. if (this.useKernelBlur) {
  56938. 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);
  56939. this._kernelBlurXPostprocess.width = targetSize;
  56940. this._kernelBlurXPostprocess.height = targetSize;
  56941. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56942. effect.setTexture("textureSampler", _this._shadowMap);
  56943. });
  56944. 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);
  56945. this._kernelBlurXPostprocess.autoClear = false;
  56946. this._kernelBlurYPostprocess.autoClear = false;
  56947. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56948. this._kernelBlurXPostprocess.packedFloat = true;
  56949. this._kernelBlurYPostprocess.packedFloat = true;
  56950. }
  56951. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56952. }
  56953. else {
  56954. 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);
  56955. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56956. effect.setFloat2("screenSize", targetSize, targetSize);
  56957. effect.setTexture("textureSampler", _this._shadowMap);
  56958. });
  56959. this._boxBlurPostprocess.autoClear = false;
  56960. this._blurPostProcesses = [this._boxBlurPostprocess];
  56961. }
  56962. };
  56963. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56964. var index;
  56965. var engine = this._scene.getEngine();
  56966. if (depthOnlySubMeshes.length) {
  56967. engine.setColorWrite(false);
  56968. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56969. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56970. }
  56971. engine.setColorWrite(true);
  56972. }
  56973. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56974. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56975. }
  56976. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56977. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56978. }
  56979. if (this._transparencyShadow) {
  56980. for (index = 0; index < transparentSubMeshes.length; index++) {
  56981. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56982. }
  56983. }
  56984. };
  56985. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56986. var _this = this;
  56987. var mesh = subMesh.getRenderingMesh();
  56988. var scene = this._scene;
  56989. var engine = scene.getEngine();
  56990. var material = subMesh.getMaterial();
  56991. if (!material) {
  56992. return;
  56993. }
  56994. // Culling
  56995. engine.setState(material.backFaceCulling);
  56996. // Managing instances
  56997. var batch = mesh._getInstancesRenderList(subMesh._id);
  56998. if (batch.mustReturn) {
  56999. return;
  57000. }
  57001. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  57002. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  57003. engine.enableEffect(this._effect);
  57004. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  57005. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  57006. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  57007. this._effect.setVector3("lightPosition", this.getLight().position);
  57008. if (scene.activeCamera) {
  57009. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  57010. }
  57011. // Alpha test
  57012. if (material && material.needAlphaTesting()) {
  57013. var alphaTexture = material.getAlphaTestTexture();
  57014. if (alphaTexture) {
  57015. this._effect.setTexture("diffuseSampler", alphaTexture);
  57016. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  57017. }
  57018. }
  57019. // Bones
  57020. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57021. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  57022. }
  57023. if (this.forceBackFacesOnly) {
  57024. engine.setState(true, 0, false, true);
  57025. }
  57026. // Draw
  57027. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57028. if (this.forceBackFacesOnly) {
  57029. engine.setState(true, 0, false, false);
  57030. }
  57031. }
  57032. else {
  57033. // Need to reset refresh rate of the shadowMap
  57034. if (this._shadowMap) {
  57035. this._shadowMap.resetRefreshCounter();
  57036. }
  57037. }
  57038. };
  57039. ShadowGenerator.prototype._applyFilterValues = function () {
  57040. if (!this._shadowMap) {
  57041. return;
  57042. }
  57043. if (this.filter === ShadowGenerator.FILTER_NONE) {
  57044. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57045. }
  57046. else {
  57047. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57048. }
  57049. };
  57050. /**
  57051. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  57052. * @param onCompiled Callback triggered at the and of the effects compilation
  57053. * @param options Sets of optional options forcing the compilation with different modes
  57054. */
  57055. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  57056. var _this = this;
  57057. var localOptions = __assign({ useInstances: false }, options);
  57058. var shadowMap = this.getShadowMap();
  57059. if (!shadowMap) {
  57060. if (onCompiled) {
  57061. onCompiled(this);
  57062. }
  57063. return;
  57064. }
  57065. var renderList = shadowMap.renderList;
  57066. if (!renderList) {
  57067. if (onCompiled) {
  57068. onCompiled(this);
  57069. }
  57070. return;
  57071. }
  57072. var subMeshes = new Array();
  57073. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  57074. var mesh = renderList_1[_i];
  57075. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  57076. }
  57077. if (subMeshes.length === 0) {
  57078. if (onCompiled) {
  57079. onCompiled(this);
  57080. }
  57081. return;
  57082. }
  57083. var currentIndex = 0;
  57084. var checkReady = function () {
  57085. if (!_this._scene || !_this._scene.getEngine()) {
  57086. return;
  57087. }
  57088. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  57089. currentIndex++;
  57090. if (currentIndex >= subMeshes.length) {
  57091. if (onCompiled) {
  57092. onCompiled(_this);
  57093. }
  57094. return;
  57095. }
  57096. }
  57097. setTimeout(checkReady, 16);
  57098. };
  57099. checkReady();
  57100. };
  57101. /**
  57102. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  57103. * @param subMesh The submesh we want to render in the shadow map
  57104. * @param useInstances Defines wether will draw in the map using instances
  57105. * @returns true if ready otherwise, false
  57106. */
  57107. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  57108. var defines = [];
  57109. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57110. defines.push("#define FLOAT");
  57111. }
  57112. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57113. defines.push("#define ESM");
  57114. }
  57115. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57116. var mesh = subMesh.getMesh();
  57117. var material = subMesh.getMaterial();
  57118. // Alpha test
  57119. if (material && material.needAlphaTesting()) {
  57120. var alphaTexture = material.getAlphaTestTexture();
  57121. if (alphaTexture) {
  57122. defines.push("#define ALPHATEST");
  57123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57124. attribs.push(BABYLON.VertexBuffer.UVKind);
  57125. defines.push("#define UV1");
  57126. }
  57127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57128. if (alphaTexture.coordinatesIndex === 1) {
  57129. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57130. defines.push("#define UV2");
  57131. }
  57132. }
  57133. }
  57134. }
  57135. // Bones
  57136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57139. if (mesh.numBoneInfluencers > 4) {
  57140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57142. }
  57143. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57144. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57145. }
  57146. else {
  57147. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57148. }
  57149. // Instances
  57150. if (useInstances) {
  57151. defines.push("#define INSTANCES");
  57152. attribs.push("world0");
  57153. attribs.push("world1");
  57154. attribs.push("world2");
  57155. attribs.push("world3");
  57156. }
  57157. // Get correct effect
  57158. var join = defines.join("\n");
  57159. if (this._cachedDefines !== join) {
  57160. this._cachedDefines = join;
  57161. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  57162. }
  57163. if (!this._effect.isReady()) {
  57164. return false;
  57165. }
  57166. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57167. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  57168. this._initializeBlurRTTAndPostProcesses();
  57169. }
  57170. }
  57171. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  57172. return false;
  57173. }
  57174. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  57175. return false;
  57176. }
  57177. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  57178. return false;
  57179. }
  57180. return true;
  57181. };
  57182. /**
  57183. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  57184. * @param defines Defines of the material we want to update
  57185. * @param lightIndex Index of the light in the enabled light list of the material
  57186. */
  57187. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  57188. var scene = this._scene;
  57189. var light = this._light;
  57190. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57191. return;
  57192. }
  57193. defines["SHADOW" + lightIndex] = true;
  57194. if (this.usePoissonSampling) {
  57195. defines["SHADOWPCF" + lightIndex] = true;
  57196. }
  57197. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57198. defines["SHADOWESM" + lightIndex] = true;
  57199. }
  57200. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57201. defines["SHADOWCLOSEESM" + lightIndex] = true;
  57202. }
  57203. if (light.needCube()) {
  57204. defines["SHADOWCUBE" + lightIndex] = true;
  57205. }
  57206. };
  57207. /**
  57208. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  57209. * defined in the generator but impacting the effect).
  57210. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  57211. * @param effect The effect we are binfing the information for
  57212. */
  57213. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  57214. var light = this._light;
  57215. var scene = this._scene;
  57216. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57217. return;
  57218. }
  57219. var camera = scene.activeCamera;
  57220. if (!camera) {
  57221. return;
  57222. }
  57223. var shadowMap = this.getShadowMap();
  57224. if (!shadowMap) {
  57225. return;
  57226. }
  57227. if (!light.needCube()) {
  57228. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  57229. }
  57230. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  57231. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  57232. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  57233. };
  57234. /**
  57235. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  57236. * (eq to shadow prjection matrix * light transform matrix)
  57237. * @returns The transform matrix used to create the shadow map
  57238. */
  57239. ShadowGenerator.prototype.getTransformMatrix = function () {
  57240. var scene = this._scene;
  57241. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  57242. return this._transformMatrix;
  57243. }
  57244. this._currentRenderID = scene.getRenderId();
  57245. this._currentFaceIndexCache = this._currentFaceIndex;
  57246. var lightPosition = this._light.position;
  57247. if (this._light.computeTransformedInformation()) {
  57248. lightPosition = this._light.transformedPosition;
  57249. }
  57250. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  57251. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  57252. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  57253. }
  57254. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  57255. this._cachedPosition = lightPosition.clone();
  57256. this._cachedDirection = this._lightDirection.clone();
  57257. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  57258. var shadowMap = this.getShadowMap();
  57259. if (shadowMap) {
  57260. var renderList = shadowMap.renderList;
  57261. if (renderList) {
  57262. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  57263. }
  57264. }
  57265. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  57266. }
  57267. return this._transformMatrix;
  57268. };
  57269. /**
  57270. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  57271. * Cube and 2D textures for instance.
  57272. */
  57273. ShadowGenerator.prototype.recreateShadowMap = function () {
  57274. var shadowMap = this._shadowMap;
  57275. if (!shadowMap) {
  57276. return;
  57277. }
  57278. // Track render list.
  57279. var renderList = shadowMap.renderList;
  57280. // Clean up existing data.
  57281. this._disposeRTTandPostProcesses();
  57282. // Reinitializes.
  57283. this._initializeGenerator();
  57284. // Reaffect the filter to ensure a correct fallback if necessary.
  57285. this.filter = this.filter;
  57286. // Reaffect the filter.
  57287. this._applyFilterValues();
  57288. // Reaffect Render List.
  57289. this._shadowMap.renderList = renderList;
  57290. };
  57291. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  57292. if (this._shadowMap2) {
  57293. this._shadowMap2.dispose();
  57294. this._shadowMap2 = null;
  57295. }
  57296. if (this._boxBlurPostprocess) {
  57297. this._boxBlurPostprocess.dispose();
  57298. this._boxBlurPostprocess = null;
  57299. }
  57300. if (this._kernelBlurXPostprocess) {
  57301. this._kernelBlurXPostprocess.dispose();
  57302. this._kernelBlurXPostprocess = null;
  57303. }
  57304. if (this._kernelBlurYPostprocess) {
  57305. this._kernelBlurYPostprocess.dispose();
  57306. this._kernelBlurYPostprocess = null;
  57307. }
  57308. this._blurPostProcesses = [];
  57309. };
  57310. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  57311. if (this._shadowMap) {
  57312. this._shadowMap.dispose();
  57313. this._shadowMap = null;
  57314. }
  57315. this._disposeBlurPostProcesses();
  57316. };
  57317. /**
  57318. * Disposes the ShadowGenerator.
  57319. * Returns nothing.
  57320. */
  57321. ShadowGenerator.prototype.dispose = function () {
  57322. this._disposeRTTandPostProcesses();
  57323. if (this._light) {
  57324. this._light._shadowGenerator = null;
  57325. this._light._markMeshesAsLightDirty();
  57326. }
  57327. };
  57328. /**
  57329. * Serializes the shadow generator setup to a json object.
  57330. * @returns The serialized JSON object
  57331. */
  57332. ShadowGenerator.prototype.serialize = function () {
  57333. var serializationObject = {};
  57334. var shadowMap = this.getShadowMap();
  57335. if (!shadowMap) {
  57336. return serializationObject;
  57337. }
  57338. serializationObject.lightId = this._light.id;
  57339. serializationObject.mapSize = shadowMap.getRenderSize();
  57340. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  57341. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  57342. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57343. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57344. serializationObject.usePoissonSampling = this.usePoissonSampling;
  57345. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  57346. serializationObject.depthScale = this.depthScale;
  57347. serializationObject.darkness = this.getDarkness();
  57348. serializationObject.blurBoxOffset = this.blurBoxOffset;
  57349. serializationObject.blurKernel = this.blurKernel;
  57350. serializationObject.blurScale = this.blurScale;
  57351. serializationObject.useKernelBlur = this.useKernelBlur;
  57352. serializationObject.transparencyShadow = this._transparencyShadow;
  57353. serializationObject.renderList = [];
  57354. if (shadowMap.renderList) {
  57355. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  57356. var mesh = shadowMap.renderList[meshIndex];
  57357. serializationObject.renderList.push(mesh.id);
  57358. }
  57359. }
  57360. return serializationObject;
  57361. };
  57362. /**
  57363. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  57364. * @param parsedShadowGenerator The JSON object to parse
  57365. * @param scene The scene to create the shadow map for
  57366. * @returns The parsed shadow generator
  57367. */
  57368. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  57369. //casting to point light, as light is missing the position attr and typescript complains.
  57370. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  57371. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  57372. var shadowMap = shadowGenerator.getShadowMap();
  57373. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  57374. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  57375. meshes.forEach(function (mesh) {
  57376. if (!shadowMap) {
  57377. return;
  57378. }
  57379. if (!shadowMap.renderList) {
  57380. shadowMap.renderList = [];
  57381. }
  57382. shadowMap.renderList.push(mesh);
  57383. });
  57384. }
  57385. if (parsedShadowGenerator.usePoissonSampling) {
  57386. shadowGenerator.usePoissonSampling = true;
  57387. }
  57388. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57389. shadowGenerator.useExponentialShadowMap = true;
  57390. }
  57391. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57392. shadowGenerator.useBlurExponentialShadowMap = true;
  57393. }
  57394. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57395. shadowGenerator.useCloseExponentialShadowMap = true;
  57396. }
  57397. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57398. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57399. }
  57400. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57401. shadowGenerator.useExponentialShadowMap = true;
  57402. }
  57403. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57404. shadowGenerator.useBlurExponentialShadowMap = true;
  57405. }
  57406. if (parsedShadowGenerator.depthScale) {
  57407. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57408. }
  57409. if (parsedShadowGenerator.blurScale) {
  57410. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57411. }
  57412. if (parsedShadowGenerator.blurBoxOffset) {
  57413. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57414. }
  57415. if (parsedShadowGenerator.useKernelBlur) {
  57416. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57417. }
  57418. if (parsedShadowGenerator.blurKernel) {
  57419. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57420. }
  57421. if (parsedShadowGenerator.bias !== undefined) {
  57422. shadowGenerator.bias = parsedShadowGenerator.bias;
  57423. }
  57424. if (parsedShadowGenerator.darkness) {
  57425. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57426. }
  57427. if (parsedShadowGenerator.transparencyShadow) {
  57428. shadowGenerator.setTransparencyShadow(true);
  57429. }
  57430. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57431. return shadowGenerator;
  57432. };
  57433. ShadowGenerator._FILTER_NONE = 0;
  57434. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57435. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57436. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57437. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57438. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57439. return ShadowGenerator;
  57440. }());
  57441. BABYLON.ShadowGenerator = ShadowGenerator;
  57442. })(BABYLON || (BABYLON = {}));
  57443. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57444. var BABYLON;
  57445. (function (BABYLON) {
  57446. var DefaultLoadingScreen = /** @class */ (function () {
  57447. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57448. if (_loadingText === void 0) { _loadingText = ""; }
  57449. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57450. var _this = this;
  57451. this._renderingCanvas = _renderingCanvas;
  57452. this._loadingText = _loadingText;
  57453. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57454. // Resize
  57455. this._resizeLoadingUI = function () {
  57456. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57457. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57458. if (!_this._loadingDiv) {
  57459. return;
  57460. }
  57461. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57462. _this._loadingDiv.style.left = canvasRect.left + "px";
  57463. _this._loadingDiv.style.top = canvasRect.top + "px";
  57464. _this._loadingDiv.style.width = canvasRect.width + "px";
  57465. _this._loadingDiv.style.height = canvasRect.height + "px";
  57466. };
  57467. }
  57468. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57469. if (this._loadingDiv) {
  57470. // Do not add a loading screen if there is already one
  57471. return;
  57472. }
  57473. this._loadingDiv = document.createElement("div");
  57474. this._loadingDiv.id = "babylonjsLoadingDiv";
  57475. this._loadingDiv.style.opacity = "0";
  57476. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57477. this._loadingDiv.style.pointerEvents = "none";
  57478. // Loading text
  57479. this._loadingTextDiv = document.createElement("div");
  57480. this._loadingTextDiv.style.position = "absolute";
  57481. this._loadingTextDiv.style.left = "0";
  57482. this._loadingTextDiv.style.top = "50%";
  57483. this._loadingTextDiv.style.marginTop = "80px";
  57484. this._loadingTextDiv.style.width = "100%";
  57485. this._loadingTextDiv.style.height = "20px";
  57486. this._loadingTextDiv.style.fontFamily = "Arial";
  57487. this._loadingTextDiv.style.fontSize = "14px";
  57488. this._loadingTextDiv.style.color = "white";
  57489. this._loadingTextDiv.style.textAlign = "center";
  57490. this._loadingTextDiv.innerHTML = "Loading";
  57491. this._loadingDiv.appendChild(this._loadingTextDiv);
  57492. //set the predefined text
  57493. this._loadingTextDiv.innerHTML = this._loadingText;
  57494. // Generating keyframes
  57495. var style = document.createElement('style');
  57496. style.type = 'text/css';
  57497. 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 }";
  57498. style.innerHTML = keyFrames;
  57499. document.getElementsByTagName('head')[0].appendChild(style);
  57500. // Loading img
  57501. var imgBack = new Image();
  57502. 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";
  57503. imgBack.style.position = "absolute";
  57504. imgBack.style.left = "50%";
  57505. imgBack.style.top = "50%";
  57506. imgBack.style.marginLeft = "-60px";
  57507. imgBack.style.marginTop = "-60px";
  57508. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57509. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57510. imgBack.style.transformOrigin = "50% 50%";
  57511. imgBack.style.webkitTransformOrigin = "50% 50%";
  57512. this._loadingDiv.appendChild(imgBack);
  57513. this._resizeLoadingUI();
  57514. window.addEventListener("resize", this._resizeLoadingUI);
  57515. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57516. document.body.appendChild(this._loadingDiv);
  57517. this._loadingDiv.style.opacity = "1";
  57518. };
  57519. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57520. var _this = this;
  57521. if (!this._loadingDiv) {
  57522. return;
  57523. }
  57524. var onTransitionEnd = function () {
  57525. if (!_this._loadingDiv) {
  57526. return;
  57527. }
  57528. document.body.removeChild(_this._loadingDiv);
  57529. window.removeEventListener("resize", _this._resizeLoadingUI);
  57530. _this._loadingDiv = null;
  57531. };
  57532. this._loadingDiv.style.opacity = "0";
  57533. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57534. };
  57535. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57536. set: function (text) {
  57537. this._loadingText = text;
  57538. if (this._loadingTextDiv) {
  57539. this._loadingTextDiv.innerHTML = this._loadingText;
  57540. }
  57541. },
  57542. enumerable: true,
  57543. configurable: true
  57544. });
  57545. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57546. get: function () {
  57547. return this._loadingDivBackgroundColor;
  57548. },
  57549. set: function (color) {
  57550. this._loadingDivBackgroundColor = color;
  57551. if (!this._loadingDiv) {
  57552. return;
  57553. }
  57554. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57555. },
  57556. enumerable: true,
  57557. configurable: true
  57558. });
  57559. return DefaultLoadingScreen;
  57560. }());
  57561. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57562. })(BABYLON || (BABYLON = {}));
  57563. //# sourceMappingURL=babylon.loadingScreen.js.map
  57564. var BABYLON;
  57565. (function (BABYLON) {
  57566. var SceneLoaderProgressEvent = /** @class */ (function () {
  57567. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57568. this.lengthComputable = lengthComputable;
  57569. this.loaded = loaded;
  57570. this.total = total;
  57571. }
  57572. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57573. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57574. };
  57575. return SceneLoaderProgressEvent;
  57576. }());
  57577. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57578. var SceneLoader = /** @class */ (function () {
  57579. function SceneLoader() {
  57580. }
  57581. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57582. get: function () {
  57583. return 0;
  57584. },
  57585. enumerable: true,
  57586. configurable: true
  57587. });
  57588. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57589. get: function () {
  57590. return 1;
  57591. },
  57592. enumerable: true,
  57593. configurable: true
  57594. });
  57595. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57596. get: function () {
  57597. return 2;
  57598. },
  57599. enumerable: true,
  57600. configurable: true
  57601. });
  57602. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57603. get: function () {
  57604. return 3;
  57605. },
  57606. enumerable: true,
  57607. configurable: true
  57608. });
  57609. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57610. get: function () {
  57611. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57612. },
  57613. set: function (value) {
  57614. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57615. },
  57616. enumerable: true,
  57617. configurable: true
  57618. });
  57619. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57620. get: function () {
  57621. return SceneLoader._ShowLoadingScreen;
  57622. },
  57623. set: function (value) {
  57624. SceneLoader._ShowLoadingScreen = value;
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. Object.defineProperty(SceneLoader, "loggingLevel", {
  57630. get: function () {
  57631. return SceneLoader._loggingLevel;
  57632. },
  57633. set: function (value) {
  57634. SceneLoader._loggingLevel = value;
  57635. },
  57636. enumerable: true,
  57637. configurable: true
  57638. });
  57639. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57640. get: function () {
  57641. return SceneLoader._CleanBoneMatrixWeights;
  57642. },
  57643. set: function (value) {
  57644. SceneLoader._CleanBoneMatrixWeights = value;
  57645. },
  57646. enumerable: true,
  57647. configurable: true
  57648. });
  57649. SceneLoader._getDefaultPlugin = function () {
  57650. return SceneLoader._registeredPlugins[".babylon"];
  57651. };
  57652. SceneLoader._getPluginForExtension = function (extension) {
  57653. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57654. if (registeredPlugin) {
  57655. return registeredPlugin;
  57656. }
  57657. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57658. return SceneLoader._getDefaultPlugin();
  57659. };
  57660. SceneLoader._getPluginForDirectLoad = function (data) {
  57661. for (var extension in SceneLoader._registeredPlugins) {
  57662. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57663. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57664. return SceneLoader._registeredPlugins[extension];
  57665. }
  57666. }
  57667. return SceneLoader._getDefaultPlugin();
  57668. };
  57669. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57670. if (sceneFilename.name) {
  57671. sceneFilename = sceneFilename.name;
  57672. }
  57673. var queryStringPosition = sceneFilename.indexOf("?");
  57674. if (queryStringPosition !== -1) {
  57675. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57676. }
  57677. var dotPosition = sceneFilename.lastIndexOf(".");
  57678. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57679. return SceneLoader._getPluginForExtension(extension);
  57680. };
  57681. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57682. SceneLoader._getDirectLoad = function (sceneFilename) {
  57683. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57684. return sceneFilename.substr(5);
  57685. }
  57686. return null;
  57687. };
  57688. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57689. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57690. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57691. var plugin;
  57692. if (registeredPlugin.plugin.createPlugin) {
  57693. plugin = registeredPlugin.plugin.createPlugin();
  57694. }
  57695. else {
  57696. plugin = registeredPlugin.plugin;
  57697. }
  57698. var useArrayBuffer = registeredPlugin.isBinary;
  57699. var database;
  57700. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57701. var dataCallback = function (data, responseURL) {
  57702. if (scene.isDisposed) {
  57703. onError("Scene has been disposed");
  57704. return;
  57705. }
  57706. scene.database = database;
  57707. onSuccess(plugin, data, responseURL);
  57708. };
  57709. var request = null;
  57710. var pluginDisposed = false;
  57711. var onDisposeObservable = plugin.onDisposeObservable;
  57712. if (onDisposeObservable) {
  57713. onDisposeObservable.add(function () {
  57714. pluginDisposed = true;
  57715. if (request) {
  57716. request.abort();
  57717. request = null;
  57718. }
  57719. onDispose();
  57720. });
  57721. }
  57722. var manifestChecked = function () {
  57723. if (pluginDisposed) {
  57724. return;
  57725. }
  57726. var url = rootUrl + sceneFilename;
  57727. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57728. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57729. } : undefined, database, useArrayBuffer, function (request, exception) {
  57730. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57731. });
  57732. };
  57733. if (directLoad) {
  57734. dataCallback(directLoad);
  57735. return plugin;
  57736. }
  57737. if (rootUrl.indexOf("file:") === -1) {
  57738. if (scene.getEngine().enableOfflineSupport) {
  57739. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57740. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57741. }
  57742. else {
  57743. manifestChecked();
  57744. }
  57745. }
  57746. else {
  57747. var fileOrString = sceneFilename;
  57748. if (fileOrString.name) {
  57749. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57750. }
  57751. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57752. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57753. }
  57754. else {
  57755. onError("Unable to find file named " + sceneFilename);
  57756. }
  57757. }
  57758. return plugin;
  57759. };
  57760. // Public functions
  57761. SceneLoader.GetPluginForExtension = function (extension) {
  57762. return SceneLoader._getPluginForExtension(extension).plugin;
  57763. };
  57764. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57765. return !!SceneLoader._registeredPlugins[extension];
  57766. };
  57767. SceneLoader.RegisterPlugin = function (plugin) {
  57768. if (typeof plugin.extensions === "string") {
  57769. var extension = plugin.extensions;
  57770. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57771. plugin: plugin,
  57772. isBinary: false
  57773. };
  57774. }
  57775. else {
  57776. var extensions = plugin.extensions;
  57777. Object.keys(extensions).forEach(function (extension) {
  57778. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57779. plugin: plugin,
  57780. isBinary: extensions[extension].isBinary
  57781. };
  57782. });
  57783. }
  57784. };
  57785. /**
  57786. * Import meshes into a scene
  57787. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57788. * @param rootUrl a string that defines the root url for scene and resources
  57789. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57790. * @param scene the instance of BABYLON.Scene to append to
  57791. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57792. * @param onProgress a callback with a progress event for each file being loaded
  57793. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57794. */
  57795. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57796. if (onSuccess === void 0) { onSuccess = null; }
  57797. if (onProgress === void 0) { onProgress = null; }
  57798. if (onError === void 0) { onError = null; }
  57799. if (pluginExtension === void 0) { pluginExtension = null; }
  57800. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57801. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57802. return null;
  57803. }
  57804. var loadingToken = {};
  57805. scene._addPendingData(loadingToken);
  57806. var disposeHandler = function () {
  57807. scene._removePendingData(loadingToken);
  57808. };
  57809. var errorHandler = function (message, exception) {
  57810. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  57811. if (onError) {
  57812. onError(scene, errorMessage, exception);
  57813. }
  57814. else {
  57815. BABYLON.Tools.Error(errorMessage);
  57816. // should the exception be thrown?
  57817. }
  57818. disposeHandler();
  57819. };
  57820. var progressHandler = onProgress ? function (event) {
  57821. try {
  57822. onProgress(event);
  57823. }
  57824. catch (e) {
  57825. errorHandler("Error in onProgress callback", e);
  57826. }
  57827. } : undefined;
  57828. var successHandler = function (meshes, particleSystems, skeletons) {
  57829. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  57830. if (onSuccess) {
  57831. try {
  57832. onSuccess(meshes, particleSystems, skeletons);
  57833. }
  57834. catch (e) {
  57835. errorHandler("Error in onSuccess callback", e);
  57836. }
  57837. }
  57838. scene._removePendingData(loadingToken);
  57839. };
  57840. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57841. if (plugin.rewriteRootURL) {
  57842. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  57843. }
  57844. if (sceneFilename === "") {
  57845. if (sceneFilename === "") {
  57846. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  57847. }
  57848. }
  57849. if (plugin.importMesh) {
  57850. var syncedPlugin = plugin;
  57851. var meshes = new Array();
  57852. var particleSystems = new Array();
  57853. var skeletons = new Array();
  57854. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  57855. return;
  57856. }
  57857. scene.loadingPluginName = plugin.name;
  57858. successHandler(meshes, particleSystems, skeletons);
  57859. }
  57860. else {
  57861. var asyncedPlugin = plugin;
  57862. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  57863. scene.loadingPluginName = plugin.name;
  57864. successHandler(meshes, particleSystems, skeletons);
  57865. }, progressHandler, errorHandler);
  57866. }
  57867. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57868. };
  57869. /**
  57870. * Load a scene
  57871. * @param rootUrl a string that defines the root url for scene and resources
  57872. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57873. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57874. * @param onSuccess a callback with the scene when import succeeds
  57875. * @param onProgress a callback with a progress event for each file being loaded
  57876. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57877. */
  57878. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57879. if (onSuccess === void 0) { onSuccess = null; }
  57880. if (onProgress === void 0) { onProgress = null; }
  57881. if (onError === void 0) { onError = null; }
  57882. if (pluginExtension === void 0) { pluginExtension = null; }
  57883. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57884. };
  57885. /**
  57886. * Append a scene
  57887. * @param rootUrl a string that defines the root url for scene and resources
  57888. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57889. * @param scene is the instance of BABYLON.Scene to append to
  57890. * @param onSuccess a callback with the scene when import succeeds
  57891. * @param onProgress a callback with a progress event for each file being loaded
  57892. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57893. */
  57894. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57895. if (onSuccess === void 0) { onSuccess = null; }
  57896. if (onProgress === void 0) { onProgress = null; }
  57897. if (onError === void 0) { onError = null; }
  57898. if (pluginExtension === void 0) { pluginExtension = null; }
  57899. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57900. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57901. return null;
  57902. }
  57903. if (SceneLoader.ShowLoadingScreen) {
  57904. scene.getEngine().displayLoadingUI();
  57905. }
  57906. var loadingToken = {};
  57907. scene._addPendingData(loadingToken);
  57908. var disposeHandler = function () {
  57909. scene._removePendingData(loadingToken);
  57910. scene.getEngine().hideLoadingUI();
  57911. };
  57912. var errorHandler = function (message, exception) {
  57913. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57914. if (onError) {
  57915. onError(scene, errorMessage, exception);
  57916. }
  57917. else {
  57918. BABYLON.Tools.Error(errorMessage);
  57919. // should the exception be thrown?
  57920. }
  57921. disposeHandler();
  57922. };
  57923. var progressHandler = onProgress ? function (event) {
  57924. try {
  57925. onProgress(event);
  57926. }
  57927. catch (e) {
  57928. errorHandler("Error in onProgress callback", e);
  57929. }
  57930. } : undefined;
  57931. var successHandler = function () {
  57932. if (onSuccess) {
  57933. try {
  57934. onSuccess(scene);
  57935. }
  57936. catch (e) {
  57937. errorHandler("Error in onSuccess callback", e);
  57938. }
  57939. }
  57940. scene._removePendingData(loadingToken);
  57941. };
  57942. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57943. if (sceneFilename === "") {
  57944. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  57945. }
  57946. if (plugin.load) {
  57947. var syncedPlugin = plugin;
  57948. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57949. return;
  57950. }
  57951. scene.loadingPluginName = plugin.name;
  57952. successHandler();
  57953. }
  57954. else {
  57955. var asyncedPlugin = plugin;
  57956. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57957. scene.loadingPluginName = plugin.name;
  57958. successHandler();
  57959. }, progressHandler, errorHandler);
  57960. }
  57961. if (SceneLoader.ShowLoadingScreen) {
  57962. scene.executeWhenReady(function () {
  57963. scene.getEngine().hideLoadingUI();
  57964. });
  57965. }
  57966. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57967. };
  57968. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57969. if (onSuccess === void 0) { onSuccess = null; }
  57970. if (onProgress === void 0) { onProgress = null; }
  57971. if (onError === void 0) { onError = null; }
  57972. if (pluginExtension === void 0) { pluginExtension = null; }
  57973. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57974. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57975. return null;
  57976. }
  57977. var loadingToken = {};
  57978. scene._addPendingData(loadingToken);
  57979. var disposeHandler = function () {
  57980. scene._removePendingData(loadingToken);
  57981. };
  57982. var errorHandler = function (message, exception) {
  57983. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57984. if (onError) {
  57985. onError(scene, errorMessage, exception);
  57986. }
  57987. else {
  57988. BABYLON.Tools.Error(errorMessage);
  57989. // should the exception be thrown?
  57990. }
  57991. disposeHandler();
  57992. };
  57993. var progressHandler = onProgress ? function (event) {
  57994. try {
  57995. onProgress(event);
  57996. }
  57997. catch (e) {
  57998. errorHandler("Error in onProgress callback", e);
  57999. }
  58000. } : undefined;
  58001. var successHandler = function (assets) {
  58002. if (onSuccess) {
  58003. try {
  58004. onSuccess(assets);
  58005. }
  58006. catch (e) {
  58007. errorHandler("Error in onSuccess callback", e);
  58008. }
  58009. }
  58010. scene._removePendingData(loadingToken);
  58011. };
  58012. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  58013. if (plugin.loadAssets) {
  58014. var syncedPlugin = plugin;
  58015. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  58016. if (!assetContainer) {
  58017. return;
  58018. }
  58019. scene.loadingPluginName = plugin.name;
  58020. successHandler(assetContainer);
  58021. }
  58022. else if (plugin.loadAssetsAsync) {
  58023. var asyncedPlugin = plugin;
  58024. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  58025. if (assetContainer) {
  58026. scene.loadingPluginName = plugin.name;
  58027. successHandler(assetContainer);
  58028. }
  58029. }, progressHandler, errorHandler);
  58030. }
  58031. else {
  58032. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  58033. }
  58034. if (SceneLoader.ShowLoadingScreen) {
  58035. scene.executeWhenReady(function () {
  58036. scene.getEngine().hideLoadingUI();
  58037. });
  58038. }
  58039. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  58040. };
  58041. // Flags
  58042. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  58043. SceneLoader._ShowLoadingScreen = true;
  58044. SceneLoader._CleanBoneMatrixWeights = false;
  58045. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  58046. // Members
  58047. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  58048. SceneLoader._registeredPlugins = {};
  58049. return SceneLoader;
  58050. }());
  58051. BABYLON.SceneLoader = SceneLoader;
  58052. ;
  58053. })(BABYLON || (BABYLON = {}));
  58054. //# sourceMappingURL=babylon.sceneLoader.js.map
  58055. var BABYLON;
  58056. (function (BABYLON) {
  58057. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  58058. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  58059. var parsedMaterial = parsedData.materials[index];
  58060. if (parsedMaterial.id === id) {
  58061. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  58062. }
  58063. }
  58064. return null;
  58065. };
  58066. var isDescendantOf = function (mesh, names, hierarchyIds) {
  58067. for (var i in names) {
  58068. if (mesh.name === names[i]) {
  58069. hierarchyIds.push(mesh.id);
  58070. return true;
  58071. }
  58072. }
  58073. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  58074. hierarchyIds.push(mesh.id);
  58075. return true;
  58076. }
  58077. return false;
  58078. };
  58079. var logOperation = function (operation, producer) {
  58080. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  58081. };
  58082. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  58083. if (addToScene === void 0) { addToScene = false; }
  58084. var container = new BABYLON.AssetContainer(scene);
  58085. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58086. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58087. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58088. // and avoid problems with multiple concurrent .babylon loads.
  58089. var log = "importScene has failed JSON parse";
  58090. try {
  58091. var parsedData = JSON.parse(data);
  58092. log = "";
  58093. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58094. var index;
  58095. var cache;
  58096. // Lights
  58097. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  58098. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  58099. var parsedLight = parsedData.lights[index];
  58100. var light = BABYLON.Light.Parse(parsedLight, scene);
  58101. if (light) {
  58102. container.lights.push(light);
  58103. log += (index === 0 ? "\n\tLights:" : "");
  58104. log += "\n\t\t" + light.toString(fullDetails);
  58105. }
  58106. }
  58107. }
  58108. // Animations
  58109. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  58110. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  58111. var parsedAnimation = parsedData.animations[index];
  58112. var animation = BABYLON.Animation.Parse(parsedAnimation);
  58113. scene.animations.push(animation);
  58114. container.animations.push(animation);
  58115. log += (index === 0 ? "\n\tAnimations:" : "");
  58116. log += "\n\t\t" + animation.toString(fullDetails);
  58117. }
  58118. }
  58119. // Materials
  58120. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  58121. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  58122. var parsedMaterial = parsedData.materials[index];
  58123. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  58124. container.materials.push(mat);
  58125. log += (index === 0 ? "\n\tMaterials:" : "");
  58126. log += "\n\t\t" + mat.toString(fullDetails);
  58127. }
  58128. }
  58129. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58130. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  58131. var parsedMultiMaterial = parsedData.multiMaterials[index];
  58132. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58133. container.multiMaterials.push(mmat);
  58134. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  58135. log += "\n\t\t" + mmat.toString(fullDetails);
  58136. }
  58137. }
  58138. // Morph targets
  58139. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  58140. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  58141. var managerData = _a[_i];
  58142. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  58143. }
  58144. }
  58145. // Skeletons
  58146. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58147. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  58148. var parsedSkeleton = parsedData.skeletons[index];
  58149. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58150. container.skeletons.push(skeleton);
  58151. log += (index === 0 ? "\n\tSkeletons:" : "");
  58152. log += "\n\t\t" + skeleton.toString(fullDetails);
  58153. }
  58154. }
  58155. // Geometries
  58156. var geometries = parsedData.geometries;
  58157. if (geometries !== undefined && geometries !== null) {
  58158. var addedGeometry = new Array();
  58159. // Boxes
  58160. var boxes = geometries.boxes;
  58161. if (boxes !== undefined && boxes !== null) {
  58162. for (index = 0, cache = boxes.length; index < cache; index++) {
  58163. var parsedBox = boxes[index];
  58164. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  58165. }
  58166. }
  58167. // Spheres
  58168. var spheres = geometries.spheres;
  58169. if (spheres !== undefined && spheres !== null) {
  58170. for (index = 0, cache = spheres.length; index < cache; index++) {
  58171. var parsedSphere = spheres[index];
  58172. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  58173. }
  58174. }
  58175. // Cylinders
  58176. var cylinders = geometries.cylinders;
  58177. if (cylinders !== undefined && cylinders !== null) {
  58178. for (index = 0, cache = cylinders.length; index < cache; index++) {
  58179. var parsedCylinder = cylinders[index];
  58180. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  58181. }
  58182. }
  58183. // Toruses
  58184. var toruses = geometries.toruses;
  58185. if (toruses !== undefined && toruses !== null) {
  58186. for (index = 0, cache = toruses.length; index < cache; index++) {
  58187. var parsedTorus = toruses[index];
  58188. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  58189. }
  58190. }
  58191. // Grounds
  58192. var grounds = geometries.grounds;
  58193. if (grounds !== undefined && grounds !== null) {
  58194. for (index = 0, cache = grounds.length; index < cache; index++) {
  58195. var parsedGround = grounds[index];
  58196. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  58197. }
  58198. }
  58199. // Planes
  58200. var planes = geometries.planes;
  58201. if (planes !== undefined && planes !== null) {
  58202. for (index = 0, cache = planes.length; index < cache; index++) {
  58203. var parsedPlane = planes[index];
  58204. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  58205. }
  58206. }
  58207. // TorusKnots
  58208. var torusKnots = geometries.torusKnots;
  58209. if (torusKnots !== undefined && torusKnots !== null) {
  58210. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  58211. var parsedTorusKnot = torusKnots[index];
  58212. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  58213. }
  58214. }
  58215. // VertexData
  58216. var vertexData = geometries.vertexData;
  58217. if (vertexData !== undefined && vertexData !== null) {
  58218. for (index = 0, cache = vertexData.length; index < cache; index++) {
  58219. var parsedVertexData = vertexData[index];
  58220. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  58221. }
  58222. }
  58223. addedGeometry.forEach(function (g) {
  58224. if (g) {
  58225. container.geometries.push(g);
  58226. }
  58227. });
  58228. }
  58229. // Transform nodes
  58230. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  58231. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  58232. var parsedTransformNode = parsedData.transformNodes[index];
  58233. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  58234. container.transformNodes.push(node);
  58235. }
  58236. }
  58237. // Meshes
  58238. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58239. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58240. var parsedMesh = parsedData.meshes[index];
  58241. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58242. container.meshes.push(mesh);
  58243. log += (index === 0 ? "\n\tMeshes:" : "");
  58244. log += "\n\t\t" + mesh.toString(fullDetails);
  58245. }
  58246. }
  58247. // Cameras
  58248. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  58249. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  58250. var parsedCamera = parsedData.cameras[index];
  58251. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  58252. container.cameras.push(camera);
  58253. log += (index === 0 ? "\n\tCameras:" : "");
  58254. log += "\n\t\t" + camera.toString(fullDetails);
  58255. }
  58256. }
  58257. // Browsing all the graph to connect the dots
  58258. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  58259. var camera = scene.cameras[index];
  58260. if (camera._waitingParentId) {
  58261. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  58262. camera._waitingParentId = null;
  58263. }
  58264. }
  58265. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58266. var light_1 = scene.lights[index];
  58267. if (light_1 && light_1._waitingParentId) {
  58268. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  58269. light_1._waitingParentId = null;
  58270. }
  58271. }
  58272. // Sounds
  58273. // TODO: add sound
  58274. var loadedSounds = [];
  58275. var loadedSound;
  58276. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  58277. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  58278. var parsedSound = parsedData.sounds[index];
  58279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58280. if (!parsedSound.url)
  58281. parsedSound.url = parsedSound.name;
  58282. if (!loadedSounds[parsedSound.url]) {
  58283. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  58284. loadedSounds[parsedSound.url] = loadedSound;
  58285. container.sounds.push(loadedSound);
  58286. }
  58287. else {
  58288. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  58289. }
  58290. }
  58291. else {
  58292. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  58293. }
  58294. }
  58295. }
  58296. loadedSounds = [];
  58297. // Connect parents & children and parse actions
  58298. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  58299. var transformNode = scene.transformNodes[index];
  58300. if (transformNode._waitingParentId) {
  58301. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  58302. transformNode._waitingParentId = null;
  58303. }
  58304. }
  58305. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58306. var mesh = scene.meshes[index];
  58307. if (mesh._waitingParentId) {
  58308. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  58309. mesh._waitingParentId = null;
  58310. }
  58311. if (mesh._waitingActions) {
  58312. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  58313. mesh._waitingActions = null;
  58314. }
  58315. }
  58316. // freeze world matrix application
  58317. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58318. var currentMesh = scene.meshes[index];
  58319. if (currentMesh._waitingFreezeWorldMatrix) {
  58320. currentMesh.freezeWorldMatrix();
  58321. currentMesh._waitingFreezeWorldMatrix = null;
  58322. }
  58323. else {
  58324. currentMesh.computeWorldMatrix(true);
  58325. }
  58326. }
  58327. // Particles Systems
  58328. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58329. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58330. var parsedParticleSystem = parsedData.particleSystems[index];
  58331. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58332. container.particleSystems.push(ps);
  58333. }
  58334. }
  58335. // Lens flares
  58336. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  58337. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  58338. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  58339. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  58340. container.lensFlareSystems.push(lf);
  58341. }
  58342. }
  58343. // Shadows
  58344. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  58345. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  58346. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  58347. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  58348. container.shadowGenerators.push(sg);
  58349. }
  58350. }
  58351. // Lights exclusions / inclusions
  58352. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58353. var light_2 = scene.lights[index];
  58354. // Excluded check
  58355. if (light_2._excludedMeshesIds.length > 0) {
  58356. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  58357. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  58358. if (excludedMesh) {
  58359. light_2.excludedMeshes.push(excludedMesh);
  58360. }
  58361. }
  58362. light_2._excludedMeshesIds = [];
  58363. }
  58364. // Included check
  58365. if (light_2._includedOnlyMeshesIds.length > 0) {
  58366. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  58367. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  58368. if (includedOnlyMesh) {
  58369. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  58370. }
  58371. }
  58372. light_2._includedOnlyMeshesIds = [];
  58373. }
  58374. }
  58375. // Actions (scene)
  58376. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  58377. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  58378. }
  58379. if (!addToScene) {
  58380. container.removeAllFromScene();
  58381. }
  58382. return container;
  58383. }
  58384. catch (err) {
  58385. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58386. if (onError) {
  58387. onError(msg, err);
  58388. }
  58389. else {
  58390. BABYLON.Tools.Log(msg);
  58391. throw err;
  58392. }
  58393. }
  58394. finally {
  58395. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58396. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58397. }
  58398. }
  58399. return null;
  58400. };
  58401. BABYLON.SceneLoader.RegisterPlugin({
  58402. name: "babylon.js",
  58403. extensions: ".babylon",
  58404. canDirectLoad: function (data) {
  58405. if (data.indexOf("babylon") !== -1) {
  58406. return true;
  58407. }
  58408. return false;
  58409. },
  58410. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58411. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58412. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58413. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58414. // and avoid problems with multiple concurrent .babylon loads.
  58415. var log = "importMesh has failed JSON parse";
  58416. try {
  58417. var parsedData = JSON.parse(data);
  58418. log = "";
  58419. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58420. if (!meshesNames) {
  58421. meshesNames = null;
  58422. }
  58423. else if (!Array.isArray(meshesNames)) {
  58424. meshesNames = [meshesNames];
  58425. }
  58426. var hierarchyIds = new Array();
  58427. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58428. var loadedSkeletonsIds = [];
  58429. var loadedMaterialsIds = [];
  58430. var index;
  58431. var cache;
  58432. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58433. var parsedMesh = parsedData.meshes[index];
  58434. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58435. if (meshesNames !== null) {
  58436. // Remove found mesh name from list.
  58437. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58438. }
  58439. //Geometry?
  58440. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58441. //does the file contain geometries?
  58442. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58443. //find the correct geometry and add it to the scene
  58444. var found = false;
  58445. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58446. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58447. return;
  58448. }
  58449. else {
  58450. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58451. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58452. switch (geometryType) {
  58453. case "boxes":
  58454. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58455. break;
  58456. case "spheres":
  58457. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58458. break;
  58459. case "cylinders":
  58460. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58461. break;
  58462. case "toruses":
  58463. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58464. break;
  58465. case "grounds":
  58466. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58467. break;
  58468. case "planes":
  58469. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58470. break;
  58471. case "torusKnots":
  58472. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58473. break;
  58474. case "vertexData":
  58475. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58476. break;
  58477. }
  58478. found = true;
  58479. }
  58480. });
  58481. }
  58482. });
  58483. if (found === false) {
  58484. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58485. }
  58486. }
  58487. }
  58488. // Material ?
  58489. if (parsedMesh.materialId) {
  58490. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58491. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58492. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58493. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58494. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58495. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58496. var subMatId = parsedMultiMaterial.materials[matIndex];
  58497. loadedMaterialsIds.push(subMatId);
  58498. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58499. log += "\n\tMaterial " + mat.toString(fullDetails);
  58500. }
  58501. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58502. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58503. materialFound = true;
  58504. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58505. break;
  58506. }
  58507. }
  58508. }
  58509. if (materialFound === false) {
  58510. loadedMaterialsIds.push(parsedMesh.materialId);
  58511. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58512. if (!mat) {
  58513. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58514. }
  58515. else {
  58516. log += "\n\tMaterial " + mat.toString(fullDetails);
  58517. }
  58518. }
  58519. }
  58520. // Skeleton ?
  58521. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58522. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58523. if (skeletonAlreadyLoaded === false) {
  58524. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58525. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58526. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58527. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58528. skeletons.push(skeleton);
  58529. loadedSkeletonsIds.push(parsedSkeleton.id);
  58530. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58531. }
  58532. }
  58533. }
  58534. }
  58535. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58536. meshes.push(mesh);
  58537. log += "\n\tMesh " + mesh.toString(fullDetails);
  58538. }
  58539. }
  58540. // Connecting parents
  58541. var currentMesh;
  58542. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58543. currentMesh = scene.meshes[index];
  58544. if (currentMesh._waitingParentId) {
  58545. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58546. currentMesh._waitingParentId = null;
  58547. }
  58548. }
  58549. // freeze and compute world matrix application
  58550. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58551. currentMesh = scene.meshes[index];
  58552. if (currentMesh._waitingFreezeWorldMatrix) {
  58553. currentMesh.freezeWorldMatrix();
  58554. currentMesh._waitingFreezeWorldMatrix = null;
  58555. }
  58556. else {
  58557. currentMesh.computeWorldMatrix(true);
  58558. }
  58559. }
  58560. }
  58561. // Particles
  58562. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58563. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58564. var parsedParticleSystem = parsedData.particleSystems[index];
  58565. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58566. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58567. }
  58568. }
  58569. }
  58570. return true;
  58571. }
  58572. catch (err) {
  58573. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58574. if (onError) {
  58575. onError(msg, err);
  58576. }
  58577. else {
  58578. BABYLON.Tools.Log(msg);
  58579. throw err;
  58580. }
  58581. }
  58582. finally {
  58583. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58584. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58585. }
  58586. }
  58587. return false;
  58588. },
  58589. load: function (scene, data, rootUrl, onError) {
  58590. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58591. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58592. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58593. // and avoid problems with multiple concurrent .babylon loads.
  58594. var log = "importScene has failed JSON parse";
  58595. try {
  58596. var parsedData = JSON.parse(data);
  58597. log = "";
  58598. // Scene
  58599. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58600. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58601. }
  58602. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58603. scene.autoClear = parsedData.autoClear;
  58604. }
  58605. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58606. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58607. }
  58608. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58609. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58610. }
  58611. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58612. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58613. }
  58614. // Fog
  58615. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58616. scene.fogMode = parsedData.fogMode;
  58617. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58618. scene.fogStart = parsedData.fogStart;
  58619. scene.fogEnd = parsedData.fogEnd;
  58620. scene.fogDensity = parsedData.fogDensity;
  58621. log += "\tFog mode for scene: ";
  58622. switch (scene.fogMode) {
  58623. // getters not compiling, so using hardcoded
  58624. case 1:
  58625. log += "exp\n";
  58626. break;
  58627. case 2:
  58628. log += "exp2\n";
  58629. break;
  58630. case 3:
  58631. log += "linear\n";
  58632. break;
  58633. }
  58634. }
  58635. //Physics
  58636. if (parsedData.physicsEnabled) {
  58637. var physicsPlugin;
  58638. if (parsedData.physicsEngine === "cannon") {
  58639. physicsPlugin = new BABYLON.CannonJSPlugin();
  58640. }
  58641. else if (parsedData.physicsEngine === "oimo") {
  58642. physicsPlugin = new BABYLON.OimoJSPlugin();
  58643. }
  58644. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58645. //else - default engine, which is currently oimo
  58646. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58647. scene.enablePhysics(physicsGravity, physicsPlugin);
  58648. }
  58649. // Metadata
  58650. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58651. scene.metadata = parsedData.metadata;
  58652. }
  58653. //collisions, if defined. otherwise, default is true
  58654. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58655. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58656. }
  58657. scene.workerCollisions = !!parsedData.workerCollisions;
  58658. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58659. if (!container) {
  58660. return false;
  58661. }
  58662. if (parsedData.autoAnimate) {
  58663. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58664. }
  58665. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58666. scene.setActiveCameraByID(parsedData.activeCameraID);
  58667. }
  58668. // Environment texture
  58669. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58670. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58671. if (parsedData.createDefaultSkybox === true) {
  58672. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58673. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58674. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58675. }
  58676. }
  58677. // Finish
  58678. return true;
  58679. }
  58680. catch (err) {
  58681. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58682. if (onError) {
  58683. onError(msg, err);
  58684. }
  58685. else {
  58686. BABYLON.Tools.Log(msg);
  58687. throw err;
  58688. }
  58689. }
  58690. finally {
  58691. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58692. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58693. }
  58694. }
  58695. return false;
  58696. },
  58697. loadAssets: function (scene, data, rootUrl, onError) {
  58698. var container = loadAssets(scene, data, rootUrl, onerror);
  58699. return container;
  58700. }
  58701. });
  58702. })(BABYLON || (BABYLON = {}));
  58703. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58704. var BABYLON;
  58705. (function (BABYLON) {
  58706. var FilesInput = /** @class */ (function () {
  58707. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58708. this.onProcessFileCallback = function () { return true; };
  58709. this._engine = engine;
  58710. this._currentScene = scene;
  58711. this._sceneLoadedCallback = sceneLoadedCallback;
  58712. this._progressCallback = progressCallback;
  58713. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58714. this._textureLoadingCallback = textureLoadingCallback;
  58715. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58716. this._onReloadCallback = onReloadCallback;
  58717. this._errorCallback = errorCallback;
  58718. }
  58719. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58720. var _this = this;
  58721. if (elementToMonitor) {
  58722. this._elementToMonitor = elementToMonitor;
  58723. this._dragEnterHandler = function (e) { _this.drag(e); };
  58724. this._dragOverHandler = function (e) { _this.drag(e); };
  58725. this._dropHandler = function (e) { _this.drop(e); };
  58726. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58727. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58728. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58729. }
  58730. };
  58731. FilesInput.prototype.dispose = function () {
  58732. if (!this._elementToMonitor) {
  58733. return;
  58734. }
  58735. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58736. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58737. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58738. };
  58739. FilesInput.prototype.renderFunction = function () {
  58740. if (this._additionalRenderLoopLogicCallback) {
  58741. this._additionalRenderLoopLogicCallback();
  58742. }
  58743. if (this._currentScene) {
  58744. if (this._textureLoadingCallback) {
  58745. var remaining = this._currentScene.getWaitingItemsCount();
  58746. if (remaining > 0) {
  58747. this._textureLoadingCallback(remaining);
  58748. }
  58749. }
  58750. this._currentScene.render();
  58751. }
  58752. };
  58753. FilesInput.prototype.drag = function (e) {
  58754. e.stopPropagation();
  58755. e.preventDefault();
  58756. };
  58757. FilesInput.prototype.drop = function (eventDrop) {
  58758. eventDrop.stopPropagation();
  58759. eventDrop.preventDefault();
  58760. this.loadFiles(eventDrop);
  58761. };
  58762. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58763. var _this = this;
  58764. var reader = folder.createReader();
  58765. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58766. reader.readEntries(function (entries) {
  58767. remaining.count += entries.length;
  58768. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58769. var entry = entries_1[_i];
  58770. if (entry.isFile) {
  58771. entry.file(function (file) {
  58772. file.correctName = relativePath + file.name;
  58773. files.push(file);
  58774. if (--remaining.count === 0) {
  58775. callback();
  58776. }
  58777. });
  58778. }
  58779. else if (entry.isDirectory) {
  58780. _this._traverseFolder(entry, files, remaining, callback);
  58781. }
  58782. }
  58783. if (--remaining.count) {
  58784. callback();
  58785. }
  58786. });
  58787. };
  58788. FilesInput.prototype._processFiles = function (files) {
  58789. for (var i = 0; i < files.length; i++) {
  58790. var name = files[i].correctName.toLowerCase();
  58791. var extension = name.split('.').pop();
  58792. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58793. continue;
  58794. }
  58795. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58796. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58797. this._sceneFileToLoad = files[i];
  58798. }
  58799. else {
  58800. FilesInput.FilesToLoad[name] = files[i];
  58801. }
  58802. }
  58803. };
  58804. FilesInput.prototype.loadFiles = function (event) {
  58805. var _this = this;
  58806. if (this._startingProcessingFilesCallback)
  58807. this._startingProcessingFilesCallback();
  58808. // Handling data transfer via drag'n'drop
  58809. if (event && event.dataTransfer && event.dataTransfer.files) {
  58810. this._filesToLoad = event.dataTransfer.files;
  58811. }
  58812. // Handling files from input files
  58813. if (event && event.target && event.target.files) {
  58814. this._filesToLoad = event.target.files;
  58815. }
  58816. if (this._filesToLoad && this._filesToLoad.length > 0) {
  58817. var files_1 = new Array();
  58818. var folders = [];
  58819. var items = event.dataTransfer ? event.dataTransfer.items : null;
  58820. for (var i = 0; i < this._filesToLoad.length; i++) {
  58821. var fileToLoad = this._filesToLoad[i];
  58822. var name_1 = fileToLoad.name.toLowerCase();
  58823. var entry = void 0;
  58824. fileToLoad.correctName = name_1;
  58825. if (items) {
  58826. var item = items[i];
  58827. if (item.getAsEntry) {
  58828. entry = item.getAsEntry();
  58829. }
  58830. else if (item.webkitGetAsEntry) {
  58831. entry = item.webkitGetAsEntry();
  58832. }
  58833. }
  58834. if (!entry) {
  58835. files_1.push(fileToLoad);
  58836. }
  58837. else {
  58838. if (entry.isDirectory) {
  58839. folders.push(entry);
  58840. }
  58841. else {
  58842. files_1.push(fileToLoad);
  58843. }
  58844. }
  58845. }
  58846. if (folders.length === 0) {
  58847. this._processFiles(files_1);
  58848. this._processReload();
  58849. }
  58850. else {
  58851. var remaining = { count: folders.length };
  58852. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  58853. var folder = folders_1[_i];
  58854. this._traverseFolder(folder, files_1, remaining, function () {
  58855. _this._processFiles(files_1);
  58856. if (remaining.count === 0) {
  58857. _this._processReload();
  58858. }
  58859. });
  58860. }
  58861. }
  58862. }
  58863. };
  58864. FilesInput.prototype._processReload = function () {
  58865. if (this._onReloadCallback) {
  58866. this._onReloadCallback(this._sceneFileToLoad);
  58867. }
  58868. else {
  58869. this.reload();
  58870. }
  58871. };
  58872. FilesInput.prototype.reload = function () {
  58873. var _this = this;
  58874. // If a scene file has been provided
  58875. if (this._sceneFileToLoad) {
  58876. if (this._currentScene) {
  58877. if (BABYLON.Tools.errorsCount > 0) {
  58878. BABYLON.Tools.ClearLogCache();
  58879. }
  58880. this._engine.stopRenderLoop();
  58881. this._currentScene.dispose();
  58882. }
  58883. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58884. _this._currentScene = newScene;
  58885. if (_this._sceneLoadedCallback) {
  58886. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58887. }
  58888. // Wait for textures and shaders to be ready
  58889. _this._currentScene.executeWhenReady(function () {
  58890. _this._engine.runRenderLoop(function () {
  58891. _this.renderFunction();
  58892. });
  58893. });
  58894. }, function (progress) {
  58895. if (_this._progressCallback) {
  58896. _this._progressCallback(progress);
  58897. }
  58898. }, function (scene, message) {
  58899. _this._currentScene = scene;
  58900. if (_this._errorCallback) {
  58901. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58902. }
  58903. });
  58904. }
  58905. else {
  58906. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58907. }
  58908. };
  58909. FilesInput.FilesToLoad = {};
  58910. return FilesInput;
  58911. }());
  58912. BABYLON.FilesInput = FilesInput;
  58913. })(BABYLON || (BABYLON = {}));
  58914. //# sourceMappingURL=babylon.filesInput.js.map
  58915. var BABYLON;
  58916. (function (BABYLON) {
  58917. /**
  58918. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58919. * The underlying implementation relies on an associative array to ensure the best performances.
  58920. * The value can be anything including 'null' but except 'undefined'
  58921. */
  58922. var StringDictionary = /** @class */ (function () {
  58923. function StringDictionary() {
  58924. this._count = 0;
  58925. this._data = {};
  58926. }
  58927. /**
  58928. * This will clear this dictionary and copy the content from the 'source' one.
  58929. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58930. * @param source the dictionary to take the content from and copy to this dictionary
  58931. */
  58932. StringDictionary.prototype.copyFrom = function (source) {
  58933. var _this = this;
  58934. this.clear();
  58935. source.forEach(function (t, v) { return _this.add(t, v); });
  58936. };
  58937. /**
  58938. * Get a value based from its key
  58939. * @param key the given key to get the matching value from
  58940. * @return the value if found, otherwise undefined is returned
  58941. */
  58942. StringDictionary.prototype.get = function (key) {
  58943. var val = this._data[key];
  58944. if (val !== undefined) {
  58945. return val;
  58946. }
  58947. return undefined;
  58948. };
  58949. /**
  58950. * Get a value from its key or add it if it doesn't exist.
  58951. * This method will ensure you that a given key/data will be present in the dictionary.
  58952. * @param key the given key to get the matching value from
  58953. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58954. * The factory will only be invoked if there's no data for the given key.
  58955. * @return the value corresponding to the key.
  58956. */
  58957. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58958. var val = this.get(key);
  58959. if (val !== undefined) {
  58960. return val;
  58961. }
  58962. val = factory(key);
  58963. if (val) {
  58964. this.add(key, val);
  58965. }
  58966. return val;
  58967. };
  58968. /**
  58969. * Get a value from its key if present in the dictionary otherwise add it
  58970. * @param key the key to get the value from
  58971. * @param val if there's no such key/value pair in the dictionary add it with this value
  58972. * @return the value corresponding to the key
  58973. */
  58974. StringDictionary.prototype.getOrAdd = function (key, val) {
  58975. var curVal = this.get(key);
  58976. if (curVal !== undefined) {
  58977. return curVal;
  58978. }
  58979. this.add(key, val);
  58980. return val;
  58981. };
  58982. /**
  58983. * Check if there's a given key in the dictionary
  58984. * @param key the key to check for
  58985. * @return true if the key is present, false otherwise
  58986. */
  58987. StringDictionary.prototype.contains = function (key) {
  58988. return this._data[key] !== undefined;
  58989. };
  58990. /**
  58991. * Add a new key and its corresponding value
  58992. * @param key the key to add
  58993. * @param value the value corresponding to the key
  58994. * @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
  58995. */
  58996. StringDictionary.prototype.add = function (key, value) {
  58997. if (this._data[key] !== undefined) {
  58998. return false;
  58999. }
  59000. this._data[key] = value;
  59001. ++this._count;
  59002. return true;
  59003. };
  59004. StringDictionary.prototype.set = function (key, value) {
  59005. if (this._data[key] === undefined) {
  59006. return false;
  59007. }
  59008. this._data[key] = value;
  59009. return true;
  59010. };
  59011. /**
  59012. * Get the element of the given key and remove it from the dictionary
  59013. * @param key
  59014. */
  59015. StringDictionary.prototype.getAndRemove = function (key) {
  59016. var val = this.get(key);
  59017. if (val !== undefined) {
  59018. delete this._data[key];
  59019. --this._count;
  59020. return val;
  59021. }
  59022. return null;
  59023. };
  59024. /**
  59025. * Remove a key/value from the dictionary.
  59026. * @param key the key to remove
  59027. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59028. */
  59029. StringDictionary.prototype.remove = function (key) {
  59030. if (this.contains(key)) {
  59031. delete this._data[key];
  59032. --this._count;
  59033. return true;
  59034. }
  59035. return false;
  59036. };
  59037. /**
  59038. * Clear the whole content of the dictionary
  59039. */
  59040. StringDictionary.prototype.clear = function () {
  59041. this._data = {};
  59042. this._count = 0;
  59043. };
  59044. Object.defineProperty(StringDictionary.prototype, "count", {
  59045. get: function () {
  59046. return this._count;
  59047. },
  59048. enumerable: true,
  59049. configurable: true
  59050. });
  59051. /**
  59052. * Execute a callback on each key/val of the dictionary.
  59053. * Note that you can remove any element in this dictionary in the callback implementation
  59054. * @param callback the callback to execute on a given key/value pair
  59055. */
  59056. StringDictionary.prototype.forEach = function (callback) {
  59057. for (var cur in this._data) {
  59058. var val = this._data[cur];
  59059. callback(cur, val);
  59060. }
  59061. };
  59062. /**
  59063. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59064. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59065. * Note that you can remove any element in this dictionary in the callback implementation
  59066. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59067. */
  59068. StringDictionary.prototype.first = function (callback) {
  59069. for (var cur in this._data) {
  59070. var val = this._data[cur];
  59071. var res = callback(cur, val);
  59072. if (res) {
  59073. return res;
  59074. }
  59075. }
  59076. return null;
  59077. };
  59078. return StringDictionary;
  59079. }());
  59080. BABYLON.StringDictionary = StringDictionary;
  59081. })(BABYLON || (BABYLON = {}));
  59082. //# sourceMappingURL=babylon.stringDictionary.js.map
  59083. var BABYLON;
  59084. (function (BABYLON) {
  59085. var Tags = /** @class */ (function () {
  59086. function Tags() {
  59087. }
  59088. Tags.EnableFor = function (obj) {
  59089. obj._tags = obj._tags || {};
  59090. obj.hasTags = function () {
  59091. return Tags.HasTags(obj);
  59092. };
  59093. obj.addTags = function (tagsString) {
  59094. return Tags.AddTagsTo(obj, tagsString);
  59095. };
  59096. obj.removeTags = function (tagsString) {
  59097. return Tags.RemoveTagsFrom(obj, tagsString);
  59098. };
  59099. obj.matchesTagsQuery = function (tagsQuery) {
  59100. return Tags.MatchesQuery(obj, tagsQuery);
  59101. };
  59102. };
  59103. Tags.DisableFor = function (obj) {
  59104. delete obj._tags;
  59105. delete obj.hasTags;
  59106. delete obj.addTags;
  59107. delete obj.removeTags;
  59108. delete obj.matchesTagsQuery;
  59109. };
  59110. Tags.HasTags = function (obj) {
  59111. if (!obj._tags) {
  59112. return false;
  59113. }
  59114. return !BABYLON.Tools.IsEmpty(obj._tags);
  59115. };
  59116. Tags.GetTags = function (obj, asString) {
  59117. if (asString === void 0) { asString = true; }
  59118. if (!obj._tags) {
  59119. return null;
  59120. }
  59121. if (asString) {
  59122. var tagsArray = [];
  59123. for (var tag in obj._tags) {
  59124. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  59125. tagsArray.push(tag);
  59126. }
  59127. }
  59128. return tagsArray.join(" ");
  59129. }
  59130. else {
  59131. return obj._tags;
  59132. }
  59133. };
  59134. // the tags 'true' and 'false' are reserved and cannot be used as tags
  59135. // a tag cannot start with '||', '&&', and '!'
  59136. // it cannot contain whitespaces
  59137. Tags.AddTagsTo = function (obj, tagsString) {
  59138. if (!tagsString) {
  59139. return;
  59140. }
  59141. if (typeof tagsString !== "string") {
  59142. return;
  59143. }
  59144. var tags = tagsString.split(" ");
  59145. tags.forEach(function (tag, index, array) {
  59146. Tags._AddTagTo(obj, tag);
  59147. });
  59148. };
  59149. Tags._AddTagTo = function (obj, tag) {
  59150. tag = tag.trim();
  59151. if (tag === "" || tag === "true" || tag === "false") {
  59152. return;
  59153. }
  59154. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  59155. return;
  59156. }
  59157. Tags.EnableFor(obj);
  59158. obj._tags[tag] = true;
  59159. };
  59160. Tags.RemoveTagsFrom = function (obj, tagsString) {
  59161. if (!Tags.HasTags(obj)) {
  59162. return;
  59163. }
  59164. var tags = tagsString.split(" ");
  59165. for (var t in tags) {
  59166. Tags._RemoveTagFrom(obj, tags[t]);
  59167. }
  59168. };
  59169. Tags._RemoveTagFrom = function (obj, tag) {
  59170. delete obj._tags[tag];
  59171. };
  59172. Tags.MatchesQuery = function (obj, tagsQuery) {
  59173. if (tagsQuery === undefined) {
  59174. return true;
  59175. }
  59176. if (tagsQuery === "") {
  59177. return Tags.HasTags(obj);
  59178. }
  59179. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  59180. };
  59181. return Tags;
  59182. }());
  59183. BABYLON.Tags = Tags;
  59184. })(BABYLON || (BABYLON = {}));
  59185. //# sourceMappingURL=babylon.tags.js.map
  59186. var BABYLON;
  59187. (function (BABYLON) {
  59188. var AndOrNotEvaluator = /** @class */ (function () {
  59189. function AndOrNotEvaluator() {
  59190. }
  59191. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  59192. if (!query.match(/\([^\(\)]*\)/g)) {
  59193. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  59194. }
  59195. else {
  59196. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  59197. // remove parenthesis
  59198. r = r.slice(1, r.length - 1);
  59199. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  59200. });
  59201. }
  59202. if (query === "true") {
  59203. return true;
  59204. }
  59205. if (query === "false") {
  59206. return false;
  59207. }
  59208. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  59209. };
  59210. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  59211. evaluateCallback = evaluateCallback || (function (r) {
  59212. return r === "true" ? true : false;
  59213. });
  59214. var result;
  59215. var or = parenthesisContent.split("||");
  59216. for (var i in or) {
  59217. if (or.hasOwnProperty(i)) {
  59218. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  59219. var and = ori.split("&&");
  59220. if (and.length > 1) {
  59221. for (var j = 0; j < and.length; ++j) {
  59222. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  59223. if (andj !== "true" && andj !== "false") {
  59224. if (andj[0] === "!") {
  59225. result = !evaluateCallback(andj.substring(1));
  59226. }
  59227. else {
  59228. result = evaluateCallback(andj);
  59229. }
  59230. }
  59231. else {
  59232. result = andj === "true" ? true : false;
  59233. }
  59234. if (!result) {
  59235. ori = "false";
  59236. break;
  59237. }
  59238. }
  59239. }
  59240. if (result || ori === "true") {
  59241. result = true;
  59242. break;
  59243. }
  59244. // result equals false (or undefined)
  59245. if (ori !== "true" && ori !== "false") {
  59246. if (ori[0] === "!") {
  59247. result = !evaluateCallback(ori.substring(1));
  59248. }
  59249. else {
  59250. result = evaluateCallback(ori);
  59251. }
  59252. }
  59253. else {
  59254. result = ori === "true" ? true : false;
  59255. }
  59256. }
  59257. }
  59258. // the whole parenthesis scope is replaced by 'true' or 'false'
  59259. return result ? "true" : "false";
  59260. };
  59261. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  59262. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  59263. // remove whitespaces
  59264. r = r.replace(/[\s]/g, function () { return ""; });
  59265. return r.length % 2 ? "!" : "";
  59266. });
  59267. booleanString = booleanString.trim();
  59268. if (booleanString === "!true") {
  59269. booleanString = "false";
  59270. }
  59271. else if (booleanString === "!false") {
  59272. booleanString = "true";
  59273. }
  59274. return booleanString;
  59275. };
  59276. return AndOrNotEvaluator;
  59277. }());
  59278. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  59279. })(BABYLON || (BABYLON = {}));
  59280. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  59281. var BABYLON;
  59282. (function (BABYLON) {
  59283. var Database = /** @class */ (function () {
  59284. function Database(urlToScene, callbackManifestChecked) {
  59285. // Handling various flavors of prefixed version of IndexedDB
  59286. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  59287. this.callbackManifestChecked = callbackManifestChecked;
  59288. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  59289. this.db = null;
  59290. this._enableSceneOffline = false;
  59291. this._enableTexturesOffline = false;
  59292. this.manifestVersionFound = 0;
  59293. this.mustUpdateRessources = false;
  59294. this.hasReachedQuota = false;
  59295. if (!Database.IDBStorageEnabled) {
  59296. this.callbackManifestChecked(true);
  59297. }
  59298. else {
  59299. this.checkManifestFile();
  59300. }
  59301. }
  59302. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  59303. get: function () {
  59304. return this._enableSceneOffline;
  59305. },
  59306. enumerable: true,
  59307. configurable: true
  59308. });
  59309. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  59310. get: function () {
  59311. return this._enableTexturesOffline;
  59312. },
  59313. enumerable: true,
  59314. configurable: true
  59315. });
  59316. Database.prototype.checkManifestFile = function () {
  59317. var _this = this;
  59318. var noManifestFile = function () {
  59319. _this._enableSceneOffline = false;
  59320. _this._enableTexturesOffline = false;
  59321. _this.callbackManifestChecked(false);
  59322. };
  59323. var timeStampUsed = false;
  59324. var manifestURL = this.currentSceneUrl + ".manifest";
  59325. var xhr = new XMLHttpRequest();
  59326. if (navigator.onLine) {
  59327. // Adding a timestamp to by-pass browsers' cache
  59328. timeStampUsed = true;
  59329. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  59330. }
  59331. xhr.open("GET", manifestURL, true);
  59332. xhr.addEventListener("load", function () {
  59333. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59334. try {
  59335. var manifestFile = JSON.parse(xhr.response);
  59336. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  59337. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  59338. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  59339. _this.manifestVersionFound = manifestFile.version;
  59340. }
  59341. if (_this.callbackManifestChecked) {
  59342. _this.callbackManifestChecked(true);
  59343. }
  59344. }
  59345. catch (ex) {
  59346. noManifestFile();
  59347. }
  59348. }
  59349. else {
  59350. noManifestFile();
  59351. }
  59352. }, false);
  59353. xhr.addEventListener("error", function (event) {
  59354. if (timeStampUsed) {
  59355. timeStampUsed = false;
  59356. // Let's retry without the timeStamp
  59357. // It could fail when coupled with HTML5 Offline API
  59358. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  59359. xhr.open("GET", retryManifestURL, true);
  59360. xhr.send();
  59361. }
  59362. else {
  59363. noManifestFile();
  59364. }
  59365. }, false);
  59366. try {
  59367. xhr.send();
  59368. }
  59369. catch (ex) {
  59370. BABYLON.Tools.Error("Error on XHR send request.");
  59371. this.callbackManifestChecked(false);
  59372. }
  59373. };
  59374. Database.prototype.openAsync = function (successCallback, errorCallback) {
  59375. var _this = this;
  59376. var handleError = function () {
  59377. _this.isSupported = false;
  59378. if (errorCallback)
  59379. errorCallback();
  59380. };
  59381. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  59382. // Your browser doesn't support IndexedDB
  59383. this.isSupported = false;
  59384. if (errorCallback)
  59385. errorCallback();
  59386. }
  59387. else {
  59388. // If the DB hasn't been opened or created yet
  59389. if (!this.db) {
  59390. this.hasReachedQuota = false;
  59391. this.isSupported = true;
  59392. var request = this.idbFactory.open("babylonjs", 1);
  59393. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59394. request.onerror = function (event) {
  59395. handleError();
  59396. };
  59397. // executes when a version change transaction cannot complete due to other active transactions
  59398. request.onblocked = function (event) {
  59399. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59400. handleError();
  59401. };
  59402. // DB has been opened successfully
  59403. request.onsuccess = function (event) {
  59404. _this.db = request.result;
  59405. successCallback();
  59406. };
  59407. // Initialization of the DB. Creating Scenes & Textures stores
  59408. request.onupgradeneeded = function (event) {
  59409. _this.db = (event.target).result;
  59410. if (_this.db) {
  59411. try {
  59412. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59413. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59414. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59415. }
  59416. catch (ex) {
  59417. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59418. handleError();
  59419. }
  59420. }
  59421. };
  59422. }
  59423. else {
  59424. if (successCallback)
  59425. successCallback();
  59426. }
  59427. }
  59428. };
  59429. Database.prototype.loadImageFromDB = function (url, image) {
  59430. var _this = this;
  59431. var completeURL = Database.ReturnFullUrlLocation(url);
  59432. var saveAndLoadImage = function () {
  59433. if (!_this.hasReachedQuota && _this.db !== null) {
  59434. // the texture is not yet in the DB, let's try to save it
  59435. _this._saveImageIntoDBAsync(completeURL, image);
  59436. }
  59437. else {
  59438. image.src = url;
  59439. }
  59440. };
  59441. if (!this.mustUpdateRessources) {
  59442. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59443. }
  59444. else {
  59445. saveAndLoadImage();
  59446. }
  59447. };
  59448. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59449. if (this.isSupported && this.db !== null) {
  59450. var texture;
  59451. var transaction = this.db.transaction(["textures"]);
  59452. transaction.onabort = function (event) {
  59453. image.src = url;
  59454. };
  59455. transaction.oncomplete = function (event) {
  59456. var blobTextureURL;
  59457. if (texture) {
  59458. var URL = window.URL || window.webkitURL;
  59459. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59460. image.onerror = function () {
  59461. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59462. image.src = url;
  59463. };
  59464. image.src = blobTextureURL;
  59465. }
  59466. else {
  59467. notInDBCallback();
  59468. }
  59469. };
  59470. var getRequest = transaction.objectStore("textures").get(url);
  59471. getRequest.onsuccess = function (event) {
  59472. texture = (event.target).result;
  59473. };
  59474. getRequest.onerror = function (event) {
  59475. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59476. image.src = url;
  59477. };
  59478. }
  59479. else {
  59480. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59481. image.src = url;
  59482. }
  59483. };
  59484. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59485. var _this = this;
  59486. if (this.isSupported) {
  59487. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59488. var generateBlobUrl = function () {
  59489. var blobTextureURL;
  59490. if (blob) {
  59491. var URL = window.URL || window.webkitURL;
  59492. try {
  59493. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59494. }
  59495. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59496. catch (ex) {
  59497. blobTextureURL = URL.createObjectURL(blob);
  59498. }
  59499. }
  59500. if (blobTextureURL) {
  59501. image.src = blobTextureURL;
  59502. }
  59503. };
  59504. if (Database.IsUASupportingBlobStorage) {
  59505. var xhr = new XMLHttpRequest(), blob;
  59506. xhr.open("GET", url, true);
  59507. xhr.responseType = "blob";
  59508. xhr.addEventListener("load", function () {
  59509. if (xhr.status === 200 && _this.db) {
  59510. // Blob as response (XHR2)
  59511. blob = xhr.response;
  59512. var transaction = _this.db.transaction(["textures"], "readwrite");
  59513. // the transaction could abort because of a QuotaExceededError error
  59514. transaction.onabort = function (event) {
  59515. try {
  59516. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59517. var srcElement = (event.srcElement || event.target);
  59518. var error = srcElement.error;
  59519. if (error && error.name === "QuotaExceededError") {
  59520. _this.hasReachedQuota = true;
  59521. }
  59522. }
  59523. catch (ex) { }
  59524. generateBlobUrl();
  59525. };
  59526. transaction.oncomplete = function (event) {
  59527. generateBlobUrl();
  59528. };
  59529. var newTexture = { textureUrl: url, data: blob };
  59530. try {
  59531. // Put the blob into the dabase
  59532. var addRequest = transaction.objectStore("textures").put(newTexture);
  59533. addRequest.onsuccess = function (event) {
  59534. };
  59535. addRequest.onerror = function (event) {
  59536. generateBlobUrl();
  59537. };
  59538. }
  59539. catch (ex) {
  59540. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59541. if (ex.code === 25) {
  59542. Database.IsUASupportingBlobStorage = false;
  59543. }
  59544. image.src = url;
  59545. }
  59546. }
  59547. else {
  59548. image.src = url;
  59549. }
  59550. }, false);
  59551. xhr.addEventListener("error", function (event) {
  59552. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59553. image.src = url;
  59554. }, false);
  59555. xhr.send();
  59556. }
  59557. else {
  59558. image.src = url;
  59559. }
  59560. }
  59561. else {
  59562. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59563. image.src = url;
  59564. }
  59565. };
  59566. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59567. var _this = this;
  59568. var updateVersion = function () {
  59569. // the version is not yet in the DB or we need to update it
  59570. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59571. };
  59572. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59573. };
  59574. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59575. var _this = this;
  59576. if (this.isSupported && this.db) {
  59577. var version;
  59578. try {
  59579. var transaction = this.db.transaction(["versions"]);
  59580. transaction.oncomplete = function (event) {
  59581. if (version) {
  59582. // If the version in the JSON file is > than the version in DB
  59583. if (_this.manifestVersionFound > version.data) {
  59584. _this.mustUpdateRessources = true;
  59585. updateInDBCallback();
  59586. }
  59587. else {
  59588. callback(version.data);
  59589. }
  59590. }
  59591. else {
  59592. _this.mustUpdateRessources = true;
  59593. updateInDBCallback();
  59594. }
  59595. };
  59596. transaction.onabort = function (event) {
  59597. callback(-1);
  59598. };
  59599. var getRequest = transaction.objectStore("versions").get(url);
  59600. getRequest.onsuccess = function (event) {
  59601. version = (event.target).result;
  59602. };
  59603. getRequest.onerror = function (event) {
  59604. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59605. callback(-1);
  59606. };
  59607. }
  59608. catch (ex) {
  59609. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59610. callback(-1);
  59611. }
  59612. }
  59613. else {
  59614. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59615. callback(-1);
  59616. }
  59617. };
  59618. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59619. var _this = this;
  59620. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59621. try {
  59622. // Open a transaction to the database
  59623. var transaction = this.db.transaction(["versions"], "readwrite");
  59624. // the transaction could abort because of a QuotaExceededError error
  59625. transaction.onabort = function (event) {
  59626. try {
  59627. var error = event.srcElement['error'];
  59628. if (error && error.name === "QuotaExceededError") {
  59629. _this.hasReachedQuota = true;
  59630. }
  59631. }
  59632. catch (ex) { }
  59633. callback(-1);
  59634. };
  59635. transaction.oncomplete = function (event) {
  59636. callback(_this.manifestVersionFound);
  59637. };
  59638. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59639. // Put the scene into the database
  59640. var addRequest = transaction.objectStore("versions").put(newVersion);
  59641. addRequest.onsuccess = function (event) {
  59642. };
  59643. addRequest.onerror = function (event) {
  59644. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59645. };
  59646. }
  59647. catch (ex) {
  59648. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59649. callback(-1);
  59650. }
  59651. }
  59652. else {
  59653. callback(-1);
  59654. }
  59655. };
  59656. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59657. var _this = this;
  59658. var completeUrl = Database.ReturnFullUrlLocation(url);
  59659. var saveAndLoadFile = function () {
  59660. // the scene is not yet in the DB, let's try to save it
  59661. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59662. };
  59663. this._checkVersionFromDB(completeUrl, function (version) {
  59664. if (version !== -1) {
  59665. if (!_this.mustUpdateRessources) {
  59666. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59667. }
  59668. else {
  59669. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59670. }
  59671. }
  59672. else {
  59673. if (errorCallback) {
  59674. errorCallback();
  59675. }
  59676. }
  59677. });
  59678. };
  59679. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59680. if (this.isSupported && this.db) {
  59681. var targetStore;
  59682. if (url.indexOf(".babylon") !== -1) {
  59683. targetStore = "scenes";
  59684. }
  59685. else {
  59686. targetStore = "textures";
  59687. }
  59688. var file;
  59689. var transaction = this.db.transaction([targetStore]);
  59690. transaction.oncomplete = function (event) {
  59691. if (file) {
  59692. callback(file.data);
  59693. }
  59694. else {
  59695. notInDBCallback();
  59696. }
  59697. };
  59698. transaction.onabort = function (event) {
  59699. notInDBCallback();
  59700. };
  59701. var getRequest = transaction.objectStore(targetStore).get(url);
  59702. getRequest.onsuccess = function (event) {
  59703. file = (event.target).result;
  59704. };
  59705. getRequest.onerror = function (event) {
  59706. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59707. notInDBCallback();
  59708. };
  59709. }
  59710. else {
  59711. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59712. callback();
  59713. }
  59714. };
  59715. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59716. var _this = this;
  59717. if (this.isSupported) {
  59718. var targetStore;
  59719. if (url.indexOf(".babylon") !== -1) {
  59720. targetStore = "scenes";
  59721. }
  59722. else {
  59723. targetStore = "textures";
  59724. }
  59725. // Create XHR
  59726. var xhr = new XMLHttpRequest();
  59727. var fileData;
  59728. xhr.open("GET", url, true);
  59729. if (useArrayBuffer) {
  59730. xhr.responseType = "arraybuffer";
  59731. }
  59732. if (progressCallback) {
  59733. xhr.onprogress = progressCallback;
  59734. }
  59735. xhr.addEventListener("load", function () {
  59736. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59737. // Blob as response (XHR2)
  59738. //fileData = xhr.responseText;
  59739. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59740. if (!_this.hasReachedQuota && _this.db) {
  59741. // Open a transaction to the database
  59742. var transaction = _this.db.transaction([targetStore], "readwrite");
  59743. // the transaction could abort because of a QuotaExceededError error
  59744. transaction.onabort = function (event) {
  59745. try {
  59746. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59747. var error = event.srcElement['error'];
  59748. if (error && error.name === "QuotaExceededError") {
  59749. _this.hasReachedQuota = true;
  59750. }
  59751. }
  59752. catch (ex) { }
  59753. callback(fileData);
  59754. };
  59755. transaction.oncomplete = function (event) {
  59756. callback(fileData);
  59757. };
  59758. var newFile;
  59759. if (targetStore === "scenes") {
  59760. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59761. }
  59762. else {
  59763. newFile = { textureUrl: url, data: fileData };
  59764. }
  59765. try {
  59766. // Put the scene into the database
  59767. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59768. addRequest.onsuccess = function (event) {
  59769. };
  59770. addRequest.onerror = function (event) {
  59771. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59772. };
  59773. }
  59774. catch (ex) {
  59775. callback(fileData);
  59776. }
  59777. }
  59778. else {
  59779. callback(fileData);
  59780. }
  59781. }
  59782. else {
  59783. callback();
  59784. }
  59785. }, false);
  59786. xhr.addEventListener("error", function (event) {
  59787. BABYLON.Tools.Error("error on XHR request.");
  59788. callback();
  59789. }, false);
  59790. xhr.send();
  59791. }
  59792. else {
  59793. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59794. callback();
  59795. }
  59796. };
  59797. Database.IsUASupportingBlobStorage = true;
  59798. Database.IDBStorageEnabled = true;
  59799. Database.parseURL = function (url) {
  59800. var a = document.createElement('a');
  59801. a.href = url;
  59802. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59803. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59804. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59805. return absLocation;
  59806. };
  59807. Database.ReturnFullUrlLocation = function (url) {
  59808. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59809. return (Database.parseURL(window.location.href) + url);
  59810. }
  59811. else {
  59812. return url;
  59813. }
  59814. };
  59815. return Database;
  59816. }());
  59817. BABYLON.Database = Database;
  59818. })(BABYLON || (BABYLON = {}));
  59819. //# sourceMappingURL=babylon.database.js.map
  59820. var BABYLON;
  59821. (function (BABYLON) {
  59822. var FresnelParameters = /** @class */ (function () {
  59823. function FresnelParameters() {
  59824. this._isEnabled = true;
  59825. this.leftColor = BABYLON.Color3.White();
  59826. this.rightColor = BABYLON.Color3.Black();
  59827. this.bias = 0;
  59828. this.power = 1;
  59829. }
  59830. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  59831. get: function () {
  59832. return this._isEnabled;
  59833. },
  59834. set: function (value) {
  59835. if (this._isEnabled === value) {
  59836. return;
  59837. }
  59838. this._isEnabled = value;
  59839. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  59840. },
  59841. enumerable: true,
  59842. configurable: true
  59843. });
  59844. FresnelParameters.prototype.clone = function () {
  59845. var newFresnelParameters = new FresnelParameters();
  59846. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  59847. return newFresnelParameters;
  59848. };
  59849. FresnelParameters.prototype.serialize = function () {
  59850. var serializationObject = {};
  59851. serializationObject.isEnabled = this.isEnabled;
  59852. serializationObject.leftColor = this.leftColor;
  59853. serializationObject.rightColor = this.rightColor;
  59854. serializationObject.bias = this.bias;
  59855. serializationObject.power = this.power;
  59856. return serializationObject;
  59857. };
  59858. FresnelParameters.Parse = function (parsedFresnelParameters) {
  59859. var fresnelParameters = new FresnelParameters();
  59860. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  59861. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  59862. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  59863. fresnelParameters.bias = parsedFresnelParameters.bias;
  59864. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  59865. return fresnelParameters;
  59866. };
  59867. return FresnelParameters;
  59868. }());
  59869. BABYLON.FresnelParameters = FresnelParameters;
  59870. })(BABYLON || (BABYLON = {}));
  59871. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59872. var BABYLON;
  59873. (function (BABYLON) {
  59874. var MultiMaterial = /** @class */ (function (_super) {
  59875. __extends(MultiMaterial, _super);
  59876. function MultiMaterial(name, scene) {
  59877. var _this = _super.call(this, name, scene, true) || this;
  59878. scene.multiMaterials.push(_this);
  59879. _this.subMaterials = new Array();
  59880. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59881. return _this;
  59882. }
  59883. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59884. get: function () {
  59885. return this._subMaterials;
  59886. },
  59887. set: function (value) {
  59888. this._subMaterials = value;
  59889. this._hookArray(value);
  59890. },
  59891. enumerable: true,
  59892. configurable: true
  59893. });
  59894. MultiMaterial.prototype._hookArray = function (array) {
  59895. var _this = this;
  59896. var oldPush = array.push;
  59897. array.push = function () {
  59898. var items = [];
  59899. for (var _i = 0; _i < arguments.length; _i++) {
  59900. items[_i] = arguments[_i];
  59901. }
  59902. var result = oldPush.apply(array, items);
  59903. _this._markAllSubMeshesAsTexturesDirty();
  59904. return result;
  59905. };
  59906. var oldSplice = array.splice;
  59907. array.splice = function (index, deleteCount) {
  59908. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59909. _this._markAllSubMeshesAsTexturesDirty();
  59910. return deleted;
  59911. };
  59912. };
  59913. // Properties
  59914. MultiMaterial.prototype.getSubMaterial = function (index) {
  59915. if (index < 0 || index >= this.subMaterials.length) {
  59916. return this.getScene().defaultMaterial;
  59917. }
  59918. return this.subMaterials[index];
  59919. };
  59920. MultiMaterial.prototype.getActiveTextures = function () {
  59921. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59922. if (subMaterial) {
  59923. return subMaterial.getActiveTextures();
  59924. }
  59925. else {
  59926. return [];
  59927. }
  59928. }));
  59929. var _a;
  59930. };
  59931. // Methods
  59932. MultiMaterial.prototype.getClassName = function () {
  59933. return "MultiMaterial";
  59934. };
  59935. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59936. for (var index = 0; index < this.subMaterials.length; index++) {
  59937. var subMaterial = this.subMaterials[index];
  59938. if (subMaterial) {
  59939. if (subMaterial.storeEffectOnSubMeshes) {
  59940. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59941. return false;
  59942. }
  59943. continue;
  59944. }
  59945. if (!subMaterial.isReady(mesh)) {
  59946. return false;
  59947. }
  59948. }
  59949. }
  59950. return true;
  59951. };
  59952. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59953. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59954. for (var index = 0; index < this.subMaterials.length; index++) {
  59955. var subMaterial = null;
  59956. var current = this.subMaterials[index];
  59957. if (cloneChildren && current) {
  59958. subMaterial = current.clone(name + "-" + current.name);
  59959. }
  59960. else {
  59961. subMaterial = this.subMaterials[index];
  59962. }
  59963. newMultiMaterial.subMaterials.push(subMaterial);
  59964. }
  59965. return newMultiMaterial;
  59966. };
  59967. MultiMaterial.prototype.serialize = function () {
  59968. var serializationObject = {};
  59969. serializationObject.name = this.name;
  59970. serializationObject.id = this.id;
  59971. if (BABYLON.Tags) {
  59972. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59973. }
  59974. serializationObject.materials = [];
  59975. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59976. var subMat = this.subMaterials[matIndex];
  59977. if (subMat) {
  59978. serializationObject.materials.push(subMat.id);
  59979. }
  59980. else {
  59981. serializationObject.materials.push(null);
  59982. }
  59983. }
  59984. return serializationObject;
  59985. };
  59986. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59987. var scene = this.getScene();
  59988. if (!scene) {
  59989. return;
  59990. }
  59991. var index = scene.multiMaterials.indexOf(this);
  59992. if (index >= 0) {
  59993. scene.multiMaterials.splice(index, 1);
  59994. }
  59995. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59996. };
  59997. return MultiMaterial;
  59998. }(BABYLON.Material));
  59999. BABYLON.MultiMaterial = MultiMaterial;
  60000. })(BABYLON || (BABYLON = {}));
  60001. //# sourceMappingURL=babylon.multiMaterial.js.map
  60002. var BABYLON;
  60003. (function (BABYLON) {
  60004. var FreeCameraTouchInput = /** @class */ (function () {
  60005. function FreeCameraTouchInput() {
  60006. this._offsetX = null;
  60007. this._offsetY = null;
  60008. this._pointerPressed = new Array();
  60009. this.touchAngularSensibility = 200000.0;
  60010. this.touchMoveSensibility = 250.0;
  60011. }
  60012. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  60013. var _this = this;
  60014. var previousPosition = null;
  60015. if (this._pointerInput === undefined) {
  60016. this._onLostFocus = function (evt) {
  60017. _this._offsetX = null;
  60018. _this._offsetY = null;
  60019. };
  60020. this._pointerInput = function (p, s) {
  60021. var evt = p.event;
  60022. if (evt.pointerType === "mouse") {
  60023. return;
  60024. }
  60025. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  60026. if (!noPreventDefault) {
  60027. evt.preventDefault();
  60028. }
  60029. _this._pointerPressed.push(evt.pointerId);
  60030. if (_this._pointerPressed.length !== 1) {
  60031. return;
  60032. }
  60033. previousPosition = {
  60034. x: evt.clientX,
  60035. y: evt.clientY
  60036. };
  60037. }
  60038. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  60039. if (!noPreventDefault) {
  60040. evt.preventDefault();
  60041. }
  60042. var index = _this._pointerPressed.indexOf(evt.pointerId);
  60043. if (index === -1) {
  60044. return;
  60045. }
  60046. _this._pointerPressed.splice(index, 1);
  60047. if (index != 0) {
  60048. return;
  60049. }
  60050. previousPosition = null;
  60051. _this._offsetX = null;
  60052. _this._offsetY = null;
  60053. }
  60054. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  60055. if (!noPreventDefault) {
  60056. evt.preventDefault();
  60057. }
  60058. if (!previousPosition) {
  60059. return;
  60060. }
  60061. var index = _this._pointerPressed.indexOf(evt.pointerId);
  60062. if (index != 0) {
  60063. return;
  60064. }
  60065. _this._offsetX = evt.clientX - previousPosition.x;
  60066. _this._offsetY = -(evt.clientY - previousPosition.y);
  60067. }
  60068. };
  60069. }
  60070. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  60071. if (this._onLostFocus) {
  60072. element.addEventListener("blur", this._onLostFocus);
  60073. }
  60074. };
  60075. FreeCameraTouchInput.prototype.detachControl = function (element) {
  60076. if (this._pointerInput && element) {
  60077. if (this._observer) {
  60078. this.camera.getScene().onPointerObservable.remove(this._observer);
  60079. this._observer = null;
  60080. }
  60081. if (this._onLostFocus) {
  60082. element.removeEventListener("blur", this._onLostFocus);
  60083. this._onLostFocus = null;
  60084. }
  60085. this._pointerPressed = [];
  60086. this._offsetX = null;
  60087. this._offsetY = null;
  60088. }
  60089. };
  60090. FreeCameraTouchInput.prototype.checkInputs = function () {
  60091. if (this._offsetX && this._offsetY) {
  60092. var camera = this.camera;
  60093. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  60094. if (this._pointerPressed.length > 1) {
  60095. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  60096. }
  60097. else {
  60098. var speed = camera._computeLocalCameraSpeed();
  60099. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  60100. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  60101. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  60102. }
  60103. }
  60104. };
  60105. FreeCameraTouchInput.prototype.getClassName = function () {
  60106. return "FreeCameraTouchInput";
  60107. };
  60108. FreeCameraTouchInput.prototype.getSimpleName = function () {
  60109. return "touch";
  60110. };
  60111. __decorate([
  60112. BABYLON.serialize()
  60113. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  60114. __decorate([
  60115. BABYLON.serialize()
  60116. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  60117. return FreeCameraTouchInput;
  60118. }());
  60119. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  60120. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  60121. })(BABYLON || (BABYLON = {}));
  60122. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  60123. var BABYLON;
  60124. (function (BABYLON) {
  60125. // We're mainly based on the logic defined into the FreeCamera code
  60126. var TouchCamera = /** @class */ (function (_super) {
  60127. __extends(TouchCamera, _super);
  60128. //-- end properties for backward compatibility for inputs
  60129. function TouchCamera(name, position, scene) {
  60130. var _this = _super.call(this, name, position, scene) || this;
  60131. _this.inputs.addTouch();
  60132. _this._setupInputs();
  60133. return _this;
  60134. }
  60135. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  60136. //-- Begin properties for backward compatibility for inputs
  60137. get: function () {
  60138. var touch = this.inputs.attached["touch"];
  60139. if (touch)
  60140. return touch.touchAngularSensibility;
  60141. return 0;
  60142. },
  60143. set: function (value) {
  60144. var touch = this.inputs.attached["touch"];
  60145. if (touch)
  60146. touch.touchAngularSensibility = value;
  60147. },
  60148. enumerable: true,
  60149. configurable: true
  60150. });
  60151. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  60152. get: function () {
  60153. var touch = this.inputs.attached["touch"];
  60154. if (touch)
  60155. return touch.touchMoveSensibility;
  60156. return 0;
  60157. },
  60158. set: function (value) {
  60159. var touch = this.inputs.attached["touch"];
  60160. if (touch)
  60161. touch.touchMoveSensibility = value;
  60162. },
  60163. enumerable: true,
  60164. configurable: true
  60165. });
  60166. TouchCamera.prototype.getClassName = function () {
  60167. return "TouchCamera";
  60168. };
  60169. TouchCamera.prototype._setupInputs = function () {
  60170. var mouse = this.inputs.attached["mouse"];
  60171. if (mouse) {
  60172. mouse.touchEnabled = false;
  60173. }
  60174. };
  60175. return TouchCamera;
  60176. }(BABYLON.FreeCamera));
  60177. BABYLON.TouchCamera = TouchCamera;
  60178. })(BABYLON || (BABYLON = {}));
  60179. //# sourceMappingURL=babylon.touchCamera.js.map
  60180. var BABYLON;
  60181. (function (BABYLON) {
  60182. var ProceduralTexture = /** @class */ (function (_super) {
  60183. __extends(ProceduralTexture, _super);
  60184. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  60185. if (fallbackTexture === void 0) { fallbackTexture = null; }
  60186. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60187. if (isCube === void 0) { isCube = false; }
  60188. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  60189. _this.isCube = isCube;
  60190. _this.isEnabled = true;
  60191. _this._currentRefreshId = -1;
  60192. _this._refreshRate = 1;
  60193. _this._vertexBuffers = {};
  60194. _this._uniforms = new Array();
  60195. _this._samplers = new Array();
  60196. _this._textures = {};
  60197. _this._floats = {};
  60198. _this._floatsArrays = {};
  60199. _this._colors3 = {};
  60200. _this._colors4 = {};
  60201. _this._vectors2 = {};
  60202. _this._vectors3 = {};
  60203. _this._matrices = {};
  60204. _this._fallbackTextureUsed = false;
  60205. scene._proceduralTextures.push(_this);
  60206. _this._engine = scene.getEngine();
  60207. _this.name = name;
  60208. _this.isRenderTarget = true;
  60209. _this._size = size;
  60210. _this._generateMipMaps = generateMipMaps;
  60211. _this.setFragment(fragment);
  60212. _this._fallbackTexture = fallbackTexture;
  60213. if (isCube) {
  60214. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  60215. _this.setFloat("face", 0);
  60216. }
  60217. else {
  60218. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  60219. }
  60220. // VBO
  60221. var vertices = [];
  60222. vertices.push(1, 1);
  60223. vertices.push(-1, 1);
  60224. vertices.push(-1, -1);
  60225. vertices.push(1, -1);
  60226. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60227. _this._createIndexBuffer();
  60228. return _this;
  60229. }
  60230. ProceduralTexture.prototype._createIndexBuffer = function () {
  60231. var engine = this._engine;
  60232. // Indices
  60233. var indices = [];
  60234. indices.push(0);
  60235. indices.push(1);
  60236. indices.push(2);
  60237. indices.push(0);
  60238. indices.push(2);
  60239. indices.push(3);
  60240. this._indexBuffer = engine.createIndexBuffer(indices);
  60241. };
  60242. ProceduralTexture.prototype._rebuild = function () {
  60243. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60244. if (vb) {
  60245. vb._rebuild();
  60246. }
  60247. this._createIndexBuffer();
  60248. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  60249. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  60250. }
  60251. };
  60252. ProceduralTexture.prototype.reset = function () {
  60253. if (this._effect === undefined) {
  60254. return;
  60255. }
  60256. var engine = this._engine;
  60257. engine._releaseEffect(this._effect);
  60258. };
  60259. ProceduralTexture.prototype.isReady = function () {
  60260. var _this = this;
  60261. var engine = this._engine;
  60262. var shaders;
  60263. if (!this._fragment) {
  60264. return false;
  60265. }
  60266. if (this._fallbackTextureUsed) {
  60267. return true;
  60268. }
  60269. if (this._fragment.fragmentElement !== undefined) {
  60270. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  60271. }
  60272. else {
  60273. shaders = { vertex: "procedural", fragment: this._fragment };
  60274. }
  60275. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  60276. _this.releaseInternalTexture();
  60277. if (_this._fallbackTexture) {
  60278. _this._texture = _this._fallbackTexture._texture;
  60279. if (_this._texture) {
  60280. _this._texture.incrementReferences();
  60281. }
  60282. }
  60283. _this._fallbackTextureUsed = true;
  60284. });
  60285. return this._effect.isReady();
  60286. };
  60287. ProceduralTexture.prototype.resetRefreshCounter = function () {
  60288. this._currentRefreshId = -1;
  60289. };
  60290. ProceduralTexture.prototype.setFragment = function (fragment) {
  60291. this._fragment = fragment;
  60292. };
  60293. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  60294. get: function () {
  60295. return this._refreshRate;
  60296. },
  60297. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  60298. set: function (value) {
  60299. this._refreshRate = value;
  60300. this.resetRefreshCounter();
  60301. },
  60302. enumerable: true,
  60303. configurable: true
  60304. });
  60305. ProceduralTexture.prototype._shouldRender = function () {
  60306. if (!this.isEnabled || !this.isReady() || !this._texture) {
  60307. return false;
  60308. }
  60309. if (this._fallbackTextureUsed) {
  60310. return false;
  60311. }
  60312. if (this._currentRefreshId === -1) {
  60313. this._currentRefreshId = 1;
  60314. return true;
  60315. }
  60316. if (this.refreshRate === this._currentRefreshId) {
  60317. this._currentRefreshId = 1;
  60318. return true;
  60319. }
  60320. this._currentRefreshId++;
  60321. return false;
  60322. };
  60323. ProceduralTexture.prototype.getRenderSize = function () {
  60324. return this._size;
  60325. };
  60326. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  60327. if (this._fallbackTextureUsed) {
  60328. return;
  60329. }
  60330. this.releaseInternalTexture();
  60331. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  60332. };
  60333. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  60334. if (this._uniforms.indexOf(uniformName) === -1) {
  60335. this._uniforms.push(uniformName);
  60336. }
  60337. };
  60338. ProceduralTexture.prototype.setTexture = function (name, texture) {
  60339. if (this._samplers.indexOf(name) === -1) {
  60340. this._samplers.push(name);
  60341. }
  60342. this._textures[name] = texture;
  60343. return this;
  60344. };
  60345. ProceduralTexture.prototype.setFloat = function (name, value) {
  60346. this._checkUniform(name);
  60347. this._floats[name] = value;
  60348. return this;
  60349. };
  60350. ProceduralTexture.prototype.setFloats = function (name, value) {
  60351. this._checkUniform(name);
  60352. this._floatsArrays[name] = value;
  60353. return this;
  60354. };
  60355. ProceduralTexture.prototype.setColor3 = function (name, value) {
  60356. this._checkUniform(name);
  60357. this._colors3[name] = value;
  60358. return this;
  60359. };
  60360. ProceduralTexture.prototype.setColor4 = function (name, value) {
  60361. this._checkUniform(name);
  60362. this._colors4[name] = value;
  60363. return this;
  60364. };
  60365. ProceduralTexture.prototype.setVector2 = function (name, value) {
  60366. this._checkUniform(name);
  60367. this._vectors2[name] = value;
  60368. return this;
  60369. };
  60370. ProceduralTexture.prototype.setVector3 = function (name, value) {
  60371. this._checkUniform(name);
  60372. this._vectors3[name] = value;
  60373. return this;
  60374. };
  60375. ProceduralTexture.prototype.setMatrix = function (name, value) {
  60376. this._checkUniform(name);
  60377. this._matrices[name] = value;
  60378. return this;
  60379. };
  60380. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60381. var scene = this.getScene();
  60382. if (!scene) {
  60383. return;
  60384. }
  60385. var engine = this._engine;
  60386. // Render
  60387. engine.enableEffect(this._effect);
  60388. engine.setState(false);
  60389. // Texture
  60390. for (var name in this._textures) {
  60391. this._effect.setTexture(name, this._textures[name]);
  60392. }
  60393. // Float
  60394. for (name in this._floats) {
  60395. this._effect.setFloat(name, this._floats[name]);
  60396. }
  60397. // Floats
  60398. for (name in this._floatsArrays) {
  60399. this._effect.setArray(name, this._floatsArrays[name]);
  60400. }
  60401. // Color3
  60402. for (name in this._colors3) {
  60403. this._effect.setColor3(name, this._colors3[name]);
  60404. }
  60405. // Color4
  60406. for (name in this._colors4) {
  60407. var color = this._colors4[name];
  60408. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60409. }
  60410. // Vector2
  60411. for (name in this._vectors2) {
  60412. this._effect.setVector2(name, this._vectors2[name]);
  60413. }
  60414. // Vector3
  60415. for (name in this._vectors3) {
  60416. this._effect.setVector3(name, this._vectors3[name]);
  60417. }
  60418. // Matrix
  60419. for (name in this._matrices) {
  60420. this._effect.setMatrix(name, this._matrices[name]);
  60421. }
  60422. if (!this._texture) {
  60423. return;
  60424. }
  60425. if (this.isCube) {
  60426. for (var face = 0; face < 6; face++) {
  60427. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60428. // VBOs
  60429. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60430. this._effect.setFloat("face", face);
  60431. // Clear
  60432. engine.clear(scene.clearColor, true, true, true);
  60433. // Draw order
  60434. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60435. // Mipmaps
  60436. if (face === 5) {
  60437. engine.generateMipMapsForCubemap(this._texture);
  60438. }
  60439. }
  60440. }
  60441. else {
  60442. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60443. // VBOs
  60444. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60445. // Clear
  60446. engine.clear(scene.clearColor, true, true, true);
  60447. // Draw order
  60448. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60449. }
  60450. // Unbind
  60451. engine.unBindFramebuffer(this._texture, this.isCube);
  60452. if (this.onGenerated) {
  60453. this.onGenerated();
  60454. }
  60455. };
  60456. ProceduralTexture.prototype.clone = function () {
  60457. var textureSize = this.getSize();
  60458. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60459. // Base texture
  60460. newTexture.hasAlpha = this.hasAlpha;
  60461. newTexture.level = this.level;
  60462. // RenderTarget Texture
  60463. newTexture.coordinatesMode = this.coordinatesMode;
  60464. return newTexture;
  60465. };
  60466. ProceduralTexture.prototype.dispose = function () {
  60467. var scene = this.getScene();
  60468. if (!scene) {
  60469. return;
  60470. }
  60471. var index = scene._proceduralTextures.indexOf(this);
  60472. if (index >= 0) {
  60473. scene._proceduralTextures.splice(index, 1);
  60474. }
  60475. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60476. if (vertexBuffer) {
  60477. vertexBuffer.dispose();
  60478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60479. }
  60480. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60481. this._indexBuffer = null;
  60482. }
  60483. _super.prototype.dispose.call(this);
  60484. };
  60485. return ProceduralTexture;
  60486. }(BABYLON.Texture));
  60487. BABYLON.ProceduralTexture = ProceduralTexture;
  60488. })(BABYLON || (BABYLON = {}));
  60489. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60490. var BABYLON;
  60491. (function (BABYLON) {
  60492. var CustomProceduralTexture = /** @class */ (function (_super) {
  60493. __extends(CustomProceduralTexture, _super);
  60494. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60495. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60496. _this._animate = true;
  60497. _this._time = 0;
  60498. _this._texturePath = texturePath;
  60499. //Try to load json
  60500. _this.loadJson(texturePath);
  60501. _this.refreshRate = 1;
  60502. return _this;
  60503. }
  60504. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60505. var _this = this;
  60506. var noConfigFile = function () {
  60507. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60508. try {
  60509. _this.setFragment(_this._texturePath);
  60510. }
  60511. catch (ex) {
  60512. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60513. }
  60514. };
  60515. var configFileUrl = jsonUrl + "/config.json";
  60516. var xhr = new XMLHttpRequest();
  60517. xhr.open("GET", configFileUrl, true);
  60518. xhr.addEventListener("load", function () {
  60519. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60520. try {
  60521. _this._config = JSON.parse(xhr.response);
  60522. _this.updateShaderUniforms();
  60523. _this.updateTextures();
  60524. _this.setFragment(_this._texturePath + "/custom");
  60525. _this._animate = _this._config.animate;
  60526. _this.refreshRate = _this._config.refreshrate;
  60527. }
  60528. catch (ex) {
  60529. noConfigFile();
  60530. }
  60531. }
  60532. else {
  60533. noConfigFile();
  60534. }
  60535. }, false);
  60536. xhr.addEventListener("error", function () {
  60537. noConfigFile();
  60538. }, false);
  60539. try {
  60540. xhr.send();
  60541. }
  60542. catch (ex) {
  60543. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60544. }
  60545. };
  60546. CustomProceduralTexture.prototype.isReady = function () {
  60547. if (!_super.prototype.isReady.call(this)) {
  60548. return false;
  60549. }
  60550. for (var name in this._textures) {
  60551. var texture = this._textures[name];
  60552. if (!texture.isReady()) {
  60553. return false;
  60554. }
  60555. }
  60556. return true;
  60557. };
  60558. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60559. var scene = this.getScene();
  60560. if (this._animate && scene) {
  60561. this._time += scene.getAnimationRatio() * 0.03;
  60562. this.updateShaderUniforms();
  60563. }
  60564. _super.prototype.render.call(this, useCameraPostProcess);
  60565. };
  60566. CustomProceduralTexture.prototype.updateTextures = function () {
  60567. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60568. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60569. }
  60570. };
  60571. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60572. if (this._config) {
  60573. for (var j = 0; j < this._config.uniforms.length; j++) {
  60574. var uniform = this._config.uniforms[j];
  60575. switch (uniform.type) {
  60576. case "float":
  60577. this.setFloat(uniform.name, uniform.value);
  60578. break;
  60579. case "color3":
  60580. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60581. break;
  60582. case "color4":
  60583. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60584. break;
  60585. case "vector2":
  60586. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60587. break;
  60588. case "vector3":
  60589. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60590. break;
  60591. }
  60592. }
  60593. }
  60594. this.setFloat("time", this._time);
  60595. };
  60596. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60597. get: function () {
  60598. return this._animate;
  60599. },
  60600. set: function (value) {
  60601. this._animate = value;
  60602. },
  60603. enumerable: true,
  60604. configurable: true
  60605. });
  60606. return CustomProceduralTexture;
  60607. }(BABYLON.ProceduralTexture));
  60608. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60609. })(BABYLON || (BABYLON = {}));
  60610. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60611. var BABYLON;
  60612. (function (BABYLON) {
  60613. var FreeCameraGamepadInput = /** @class */ (function () {
  60614. function FreeCameraGamepadInput() {
  60615. this.gamepadAngularSensibility = 200;
  60616. this.gamepadMoveSensibility = 40;
  60617. // private members
  60618. this._cameraTransform = BABYLON.Matrix.Identity();
  60619. this._deltaTransform = BABYLON.Vector3.Zero();
  60620. this._vector3 = BABYLON.Vector3.Zero();
  60621. this._vector2 = BABYLON.Vector2.Zero();
  60622. }
  60623. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60624. var _this = this;
  60625. var manager = this.camera.getScene().gamepadManager;
  60626. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60627. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60628. // prioritize XBOX gamepads.
  60629. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60630. _this.gamepad = gamepad;
  60631. }
  60632. }
  60633. });
  60634. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60635. if (_this.gamepad === gamepad) {
  60636. _this.gamepad = null;
  60637. }
  60638. });
  60639. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60640. };
  60641. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60642. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60643. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60644. this.gamepad = null;
  60645. };
  60646. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60647. if (this.gamepad && this.gamepad.leftStick) {
  60648. var camera = this.camera;
  60649. var LSValues = this.gamepad.leftStick;
  60650. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60651. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60652. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60653. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60654. var RSValues = this.gamepad.rightStick;
  60655. if (RSValues) {
  60656. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60657. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60658. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60659. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60660. }
  60661. else {
  60662. RSValues = { x: 0, y: 0 };
  60663. }
  60664. if (!camera.rotationQuaternion) {
  60665. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60666. }
  60667. else {
  60668. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60669. }
  60670. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60671. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60672. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60673. camera.cameraDirection.addInPlace(this._deltaTransform);
  60674. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60675. camera.cameraRotation.addInPlace(this._vector2);
  60676. }
  60677. };
  60678. FreeCameraGamepadInput.prototype.getClassName = function () {
  60679. return "FreeCameraGamepadInput";
  60680. };
  60681. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60682. return "gamepad";
  60683. };
  60684. __decorate([
  60685. BABYLON.serialize()
  60686. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60687. __decorate([
  60688. BABYLON.serialize()
  60689. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60690. return FreeCameraGamepadInput;
  60691. }());
  60692. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60693. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60694. })(BABYLON || (BABYLON = {}));
  60695. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60696. var BABYLON;
  60697. (function (BABYLON) {
  60698. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60699. function ArcRotateCameraGamepadInput() {
  60700. this.gamepadRotationSensibility = 80;
  60701. this.gamepadMoveSensibility = 40;
  60702. }
  60703. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60704. var _this = this;
  60705. var manager = this.camera.getScene().gamepadManager;
  60706. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60707. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60708. // prioritize XBOX gamepads.
  60709. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60710. _this.gamepad = gamepad;
  60711. }
  60712. }
  60713. });
  60714. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60715. if (_this.gamepad === gamepad) {
  60716. _this.gamepad = null;
  60717. }
  60718. });
  60719. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60720. };
  60721. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60722. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60723. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60724. this.gamepad = null;
  60725. };
  60726. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60727. if (this.gamepad) {
  60728. var camera = this.camera;
  60729. var RSValues = this.gamepad.rightStick;
  60730. if (RSValues) {
  60731. if (RSValues.x != 0) {
  60732. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60733. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60734. camera.inertialAlphaOffset += normalizedRX;
  60735. }
  60736. }
  60737. if (RSValues.y != 0) {
  60738. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60739. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60740. camera.inertialBetaOffset += normalizedRY;
  60741. }
  60742. }
  60743. }
  60744. var LSValues = this.gamepad.leftStick;
  60745. if (LSValues && LSValues.y != 0) {
  60746. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60747. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60748. this.camera.inertialRadiusOffset -= normalizedLY;
  60749. }
  60750. }
  60751. }
  60752. };
  60753. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60754. return "ArcRotateCameraGamepadInput";
  60755. };
  60756. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60757. return "gamepad";
  60758. };
  60759. __decorate([
  60760. BABYLON.serialize()
  60761. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60762. __decorate([
  60763. BABYLON.serialize()
  60764. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60765. return ArcRotateCameraGamepadInput;
  60766. }());
  60767. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60768. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60769. })(BABYLON || (BABYLON = {}));
  60770. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60771. var BABYLON;
  60772. (function (BABYLON) {
  60773. var GamepadManager = /** @class */ (function () {
  60774. function GamepadManager(_scene) {
  60775. var _this = this;
  60776. this._scene = _scene;
  60777. this._babylonGamepads = [];
  60778. this._oneGamepadConnected = false;
  60779. this._isMonitoring = false;
  60780. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60781. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60782. this._gamepadEventSupported = false;
  60783. }
  60784. else {
  60785. this._gamepadEventSupported = 'GamepadEvent' in window;
  60786. this._gamepadSupport = (navigator.getGamepads ||
  60787. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60788. }
  60789. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60790. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60791. for (var i in _this._babylonGamepads) {
  60792. var gamepad = _this._babylonGamepads[i];
  60793. if (gamepad && gamepad._isConnected) {
  60794. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60795. }
  60796. }
  60797. });
  60798. this._onGamepadConnectedEvent = function (evt) {
  60799. var gamepad = evt.gamepad;
  60800. if (gamepad.index in _this._babylonGamepads) {
  60801. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60802. return;
  60803. }
  60804. }
  60805. var newGamepad;
  60806. if (_this._babylonGamepads[gamepad.index]) {
  60807. newGamepad = _this._babylonGamepads[gamepad.index];
  60808. newGamepad.browserGamepad = gamepad;
  60809. newGamepad._isConnected = true;
  60810. }
  60811. else {
  60812. newGamepad = _this._addNewGamepad(gamepad);
  60813. }
  60814. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60815. _this._startMonitoringGamepads();
  60816. };
  60817. this._onGamepadDisconnectedEvent = function (evt) {
  60818. var gamepad = evt.gamepad;
  60819. // Remove the gamepad from the list of gamepads to monitor.
  60820. for (var i in _this._babylonGamepads) {
  60821. if (_this._babylonGamepads[i].index === gamepad.index) {
  60822. var disconnectedGamepad = _this._babylonGamepads[i];
  60823. disconnectedGamepad._isConnected = false;
  60824. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  60825. break;
  60826. }
  60827. }
  60828. };
  60829. if (this._gamepadSupport) {
  60830. //first add already-connected gamepads
  60831. this._updateGamepadObjects();
  60832. if (this._babylonGamepads.length) {
  60833. this._startMonitoringGamepads();
  60834. }
  60835. // Checking if the gamepad connected event is supported (like in Firefox)
  60836. if (this._gamepadEventSupported) {
  60837. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  60838. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  60839. }
  60840. else {
  60841. this._startMonitoringGamepads();
  60842. }
  60843. }
  60844. }
  60845. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  60846. get: function () {
  60847. return this._babylonGamepads;
  60848. },
  60849. enumerable: true,
  60850. configurable: true
  60851. });
  60852. GamepadManager.prototype.getGamepadByType = function (type) {
  60853. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  60854. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  60855. var gamepad = _a[_i];
  60856. if (gamepad && gamepad.type === type) {
  60857. return gamepad;
  60858. }
  60859. }
  60860. return null;
  60861. };
  60862. GamepadManager.prototype.dispose = function () {
  60863. if (this._gamepadEventSupported) {
  60864. if (this._onGamepadConnectedEvent) {
  60865. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  60866. }
  60867. if (this._onGamepadDisconnectedEvent) {
  60868. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60869. }
  60870. this._onGamepadConnectedEvent = null;
  60871. this._onGamepadDisconnectedEvent = null;
  60872. }
  60873. this._babylonGamepads.forEach(function (gamepad) {
  60874. gamepad.dispose();
  60875. });
  60876. this.onGamepadConnectedObservable.clear();
  60877. this.onGamepadDisconnectedObservable.clear();
  60878. this._oneGamepadConnected = false;
  60879. this._stopMonitoringGamepads();
  60880. this._babylonGamepads = [];
  60881. };
  60882. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60883. if (!this._oneGamepadConnected) {
  60884. this._oneGamepadConnected = true;
  60885. }
  60886. var newGamepad;
  60887. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60888. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60889. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60890. }
  60891. else if (gamepad.pose) {
  60892. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60893. }
  60894. else {
  60895. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60896. }
  60897. this._babylonGamepads[newGamepad.index] = newGamepad;
  60898. return newGamepad;
  60899. };
  60900. GamepadManager.prototype._startMonitoringGamepads = function () {
  60901. if (!this._isMonitoring) {
  60902. this._isMonitoring = true;
  60903. //back-comp
  60904. if (!this._scene) {
  60905. this._checkGamepadsStatus();
  60906. }
  60907. }
  60908. };
  60909. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60910. this._isMonitoring = false;
  60911. };
  60912. GamepadManager.prototype._checkGamepadsStatus = function () {
  60913. var _this = this;
  60914. // Hack to be compatible Chrome
  60915. this._updateGamepadObjects();
  60916. for (var i in this._babylonGamepads) {
  60917. var gamepad = this._babylonGamepads[i];
  60918. if (!gamepad || !gamepad.isConnected) {
  60919. continue;
  60920. }
  60921. gamepad.update();
  60922. }
  60923. if (this._isMonitoring && !this._scene) {
  60924. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60925. }
  60926. };
  60927. // This function is called only on Chrome, which does not properly support
  60928. // connection/disconnection events and forces you to recopy again the gamepad object
  60929. GamepadManager.prototype._updateGamepadObjects = function () {
  60930. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60931. for (var i = 0; i < gamepads.length; i++) {
  60932. if (gamepads[i]) {
  60933. if (!this._babylonGamepads[gamepads[i].index]) {
  60934. var newGamepad = this._addNewGamepad(gamepads[i]);
  60935. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60936. }
  60937. else {
  60938. // Forced to copy again this object for Chrome for unknown reason
  60939. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60940. if (!this._babylonGamepads[i].isConnected) {
  60941. this._babylonGamepads[i]._isConnected = true;
  60942. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60943. }
  60944. }
  60945. }
  60946. }
  60947. };
  60948. return GamepadManager;
  60949. }());
  60950. BABYLON.GamepadManager = GamepadManager;
  60951. })(BABYLON || (BABYLON = {}));
  60952. //# sourceMappingURL=babylon.gamepadManager.js.map
  60953. var BABYLON;
  60954. (function (BABYLON) {
  60955. var StickValues = /** @class */ (function () {
  60956. function StickValues(x, y) {
  60957. this.x = x;
  60958. this.y = y;
  60959. }
  60960. return StickValues;
  60961. }());
  60962. BABYLON.StickValues = StickValues;
  60963. var Gamepad = /** @class */ (function () {
  60964. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60965. if (leftStickX === void 0) { leftStickX = 0; }
  60966. if (leftStickY === void 0) { leftStickY = 1; }
  60967. if (rightStickX === void 0) { rightStickX = 2; }
  60968. if (rightStickY === void 0) { rightStickY = 3; }
  60969. this.id = id;
  60970. this.index = index;
  60971. this.browserGamepad = browserGamepad;
  60972. this._isConnected = true;
  60973. this._invertLeftStickY = false;
  60974. this.type = Gamepad.GAMEPAD;
  60975. this._leftStickAxisX = leftStickX;
  60976. this._leftStickAxisY = leftStickY;
  60977. this._rightStickAxisX = rightStickX;
  60978. this._rightStickAxisY = rightStickY;
  60979. if (this.browserGamepad.axes.length >= 2) {
  60980. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60981. }
  60982. if (this.browserGamepad.axes.length >= 4) {
  60983. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60984. }
  60985. }
  60986. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60987. get: function () {
  60988. return this._isConnected;
  60989. },
  60990. enumerable: true,
  60991. configurable: true
  60992. });
  60993. Gamepad.prototype.onleftstickchanged = function (callback) {
  60994. this._onleftstickchanged = callback;
  60995. };
  60996. Gamepad.prototype.onrightstickchanged = function (callback) {
  60997. this._onrightstickchanged = callback;
  60998. };
  60999. Object.defineProperty(Gamepad.prototype, "leftStick", {
  61000. get: function () {
  61001. return this._leftStick;
  61002. },
  61003. set: function (newValues) {
  61004. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  61005. this._onleftstickchanged(newValues);
  61006. }
  61007. this._leftStick = newValues;
  61008. },
  61009. enumerable: true,
  61010. configurable: true
  61011. });
  61012. Object.defineProperty(Gamepad.prototype, "rightStick", {
  61013. get: function () {
  61014. return this._rightStick;
  61015. },
  61016. set: function (newValues) {
  61017. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  61018. this._onrightstickchanged(newValues);
  61019. }
  61020. this._rightStick = newValues;
  61021. },
  61022. enumerable: true,
  61023. configurable: true
  61024. });
  61025. Gamepad.prototype.update = function () {
  61026. if (this._leftStick) {
  61027. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  61028. if (this._invertLeftStickY) {
  61029. this.leftStick.y *= -1;
  61030. }
  61031. }
  61032. if (this._rightStick) {
  61033. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  61034. }
  61035. };
  61036. Gamepad.prototype.dispose = function () {
  61037. };
  61038. Gamepad.GAMEPAD = 0;
  61039. Gamepad.GENERIC = 1;
  61040. Gamepad.XBOX = 2;
  61041. Gamepad.POSE_ENABLED = 3;
  61042. return Gamepad;
  61043. }());
  61044. BABYLON.Gamepad = Gamepad;
  61045. var GenericPad = /** @class */ (function (_super) {
  61046. __extends(GenericPad, _super);
  61047. function GenericPad(id, index, browserGamepad) {
  61048. var _this = _super.call(this, id, index, browserGamepad) || this;
  61049. _this.onButtonDownObservable = new BABYLON.Observable();
  61050. _this.onButtonUpObservable = new BABYLON.Observable();
  61051. _this.type = Gamepad.GENERIC;
  61052. _this._buttons = new Array(browserGamepad.buttons.length);
  61053. return _this;
  61054. }
  61055. GenericPad.prototype.onbuttondown = function (callback) {
  61056. this._onbuttondown = callback;
  61057. };
  61058. GenericPad.prototype.onbuttonup = function (callback) {
  61059. this._onbuttonup = callback;
  61060. };
  61061. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  61062. if (newValue !== currentValue) {
  61063. if (newValue === 1) {
  61064. if (this._onbuttondown) {
  61065. this._onbuttondown(buttonIndex);
  61066. }
  61067. this.onButtonDownObservable.notifyObservers(buttonIndex);
  61068. }
  61069. if (newValue === 0) {
  61070. if (this._onbuttonup) {
  61071. this._onbuttonup(buttonIndex);
  61072. }
  61073. this.onButtonUpObservable.notifyObservers(buttonIndex);
  61074. }
  61075. }
  61076. return newValue;
  61077. };
  61078. GenericPad.prototype.update = function () {
  61079. _super.prototype.update.call(this);
  61080. for (var index = 0; index < this._buttons.length; index++) {
  61081. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  61082. }
  61083. };
  61084. GenericPad.prototype.dispose = function () {
  61085. _super.prototype.dispose.call(this);
  61086. this.onButtonDownObservable.clear();
  61087. this.onButtonUpObservable.clear();
  61088. };
  61089. return GenericPad;
  61090. }(Gamepad));
  61091. BABYLON.GenericPad = GenericPad;
  61092. })(BABYLON || (BABYLON = {}));
  61093. //# sourceMappingURL=babylon.gamepad.js.map
  61094. var BABYLON;
  61095. (function (BABYLON) {
  61096. var Xbox360Button;
  61097. (function (Xbox360Button) {
  61098. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  61099. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  61100. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  61101. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  61102. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  61103. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  61104. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  61105. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  61106. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  61107. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  61108. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  61109. var Xbox360Dpad;
  61110. (function (Xbox360Dpad) {
  61111. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  61112. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  61113. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  61114. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  61115. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  61116. var Xbox360Pad = /** @class */ (function (_super) {
  61117. __extends(Xbox360Pad, _super);
  61118. function Xbox360Pad(id, index, gamepad, xboxOne) {
  61119. if (xboxOne === void 0) { xboxOne = false; }
  61120. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  61121. _this._leftTrigger = 0;
  61122. _this._rightTrigger = 0;
  61123. _this.onButtonDownObservable = new BABYLON.Observable();
  61124. _this.onButtonUpObservable = new BABYLON.Observable();
  61125. _this.onPadDownObservable = new BABYLON.Observable();
  61126. _this.onPadUpObservable = new BABYLON.Observable();
  61127. _this._buttonA = 0;
  61128. _this._buttonB = 0;
  61129. _this._buttonX = 0;
  61130. _this._buttonY = 0;
  61131. _this._buttonBack = 0;
  61132. _this._buttonStart = 0;
  61133. _this._buttonLB = 0;
  61134. _this._buttonRB = 0;
  61135. _this._buttonLeftStick = 0;
  61136. _this._buttonRightStick = 0;
  61137. _this._dPadUp = 0;
  61138. _this._dPadDown = 0;
  61139. _this._dPadLeft = 0;
  61140. _this._dPadRight = 0;
  61141. _this._isXboxOnePad = false;
  61142. _this.type = BABYLON.Gamepad.XBOX;
  61143. _this._isXboxOnePad = xboxOne;
  61144. return _this;
  61145. }
  61146. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  61147. this._onlefttriggerchanged = callback;
  61148. };
  61149. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  61150. this._onrighttriggerchanged = callback;
  61151. };
  61152. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  61153. get: function () {
  61154. return this._leftTrigger;
  61155. },
  61156. set: function (newValue) {
  61157. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  61158. this._onlefttriggerchanged(newValue);
  61159. }
  61160. this._leftTrigger = newValue;
  61161. },
  61162. enumerable: true,
  61163. configurable: true
  61164. });
  61165. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  61166. get: function () {
  61167. return this._rightTrigger;
  61168. },
  61169. set: function (newValue) {
  61170. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  61171. this._onrighttriggerchanged(newValue);
  61172. }
  61173. this._rightTrigger = newValue;
  61174. },
  61175. enumerable: true,
  61176. configurable: true
  61177. });
  61178. Xbox360Pad.prototype.onbuttondown = function (callback) {
  61179. this._onbuttondown = callback;
  61180. };
  61181. Xbox360Pad.prototype.onbuttonup = function (callback) {
  61182. this._onbuttonup = callback;
  61183. };
  61184. Xbox360Pad.prototype.ondpaddown = function (callback) {
  61185. this._ondpaddown = callback;
  61186. };
  61187. Xbox360Pad.prototype.ondpadup = function (callback) {
  61188. this._ondpadup = callback;
  61189. };
  61190. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  61191. if (newValue !== currentValue) {
  61192. if (newValue === 1) {
  61193. if (this._onbuttondown) {
  61194. this._onbuttondown(buttonType);
  61195. }
  61196. this.onButtonDownObservable.notifyObservers(buttonType);
  61197. }
  61198. if (newValue === 0) {
  61199. if (this._onbuttonup) {
  61200. this._onbuttonup(buttonType);
  61201. }
  61202. this.onButtonUpObservable.notifyObservers(buttonType);
  61203. }
  61204. }
  61205. return newValue;
  61206. };
  61207. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  61208. if (newValue !== currentValue) {
  61209. if (newValue === 1) {
  61210. if (this._ondpaddown) {
  61211. this._ondpaddown(buttonType);
  61212. }
  61213. this.onPadDownObservable.notifyObservers(buttonType);
  61214. }
  61215. if (newValue === 0) {
  61216. if (this._ondpadup) {
  61217. this._ondpadup(buttonType);
  61218. }
  61219. this.onPadUpObservable.notifyObservers(buttonType);
  61220. }
  61221. }
  61222. return newValue;
  61223. };
  61224. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  61225. get: function () {
  61226. return this._buttonA;
  61227. },
  61228. set: function (value) {
  61229. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  61230. },
  61231. enumerable: true,
  61232. configurable: true
  61233. });
  61234. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  61235. get: function () {
  61236. return this._buttonB;
  61237. },
  61238. set: function (value) {
  61239. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  61240. },
  61241. enumerable: true,
  61242. configurable: true
  61243. });
  61244. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  61245. get: function () {
  61246. return this._buttonX;
  61247. },
  61248. set: function (value) {
  61249. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  61250. },
  61251. enumerable: true,
  61252. configurable: true
  61253. });
  61254. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  61255. get: function () {
  61256. return this._buttonY;
  61257. },
  61258. set: function (value) {
  61259. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  61260. },
  61261. enumerable: true,
  61262. configurable: true
  61263. });
  61264. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  61265. get: function () {
  61266. return this._buttonStart;
  61267. },
  61268. set: function (value) {
  61269. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  61270. },
  61271. enumerable: true,
  61272. configurable: true
  61273. });
  61274. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  61275. get: function () {
  61276. return this._buttonBack;
  61277. },
  61278. set: function (value) {
  61279. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  61280. },
  61281. enumerable: true,
  61282. configurable: true
  61283. });
  61284. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  61285. get: function () {
  61286. return this._buttonLB;
  61287. },
  61288. set: function (value) {
  61289. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  61290. },
  61291. enumerable: true,
  61292. configurable: true
  61293. });
  61294. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  61295. get: function () {
  61296. return this._buttonRB;
  61297. },
  61298. set: function (value) {
  61299. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  61300. },
  61301. enumerable: true,
  61302. configurable: true
  61303. });
  61304. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  61305. get: function () {
  61306. return this._buttonLeftStick;
  61307. },
  61308. set: function (value) {
  61309. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  61310. },
  61311. enumerable: true,
  61312. configurable: true
  61313. });
  61314. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  61315. get: function () {
  61316. return this._buttonRightStick;
  61317. },
  61318. set: function (value) {
  61319. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  61320. },
  61321. enumerable: true,
  61322. configurable: true
  61323. });
  61324. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  61325. get: function () {
  61326. return this._dPadUp;
  61327. },
  61328. set: function (value) {
  61329. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  61330. },
  61331. enumerable: true,
  61332. configurable: true
  61333. });
  61334. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  61335. get: function () {
  61336. return this._dPadDown;
  61337. },
  61338. set: function (value) {
  61339. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  61340. },
  61341. enumerable: true,
  61342. configurable: true
  61343. });
  61344. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  61345. get: function () {
  61346. return this._dPadLeft;
  61347. },
  61348. set: function (value) {
  61349. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  61350. },
  61351. enumerable: true,
  61352. configurable: true
  61353. });
  61354. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  61355. get: function () {
  61356. return this._dPadRight;
  61357. },
  61358. set: function (value) {
  61359. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  61360. },
  61361. enumerable: true,
  61362. configurable: true
  61363. });
  61364. Xbox360Pad.prototype.update = function () {
  61365. _super.prototype.update.call(this);
  61366. if (this._isXboxOnePad) {
  61367. this.buttonA = this.browserGamepad.buttons[0].value;
  61368. this.buttonB = this.browserGamepad.buttons[1].value;
  61369. this.buttonX = this.browserGamepad.buttons[2].value;
  61370. this.buttonY = this.browserGamepad.buttons[3].value;
  61371. this.buttonLB = this.browserGamepad.buttons[4].value;
  61372. this.buttonRB = this.browserGamepad.buttons[5].value;
  61373. this.leftTrigger = this.browserGamepad.axes[2];
  61374. this.rightTrigger = this.browserGamepad.axes[5];
  61375. this.buttonBack = this.browserGamepad.buttons[9].value;
  61376. this.buttonStart = this.browserGamepad.buttons[8].value;
  61377. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  61378. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  61379. this.dPadUp = this.browserGamepad.buttons[11].value;
  61380. this.dPadDown = this.browserGamepad.buttons[12].value;
  61381. this.dPadLeft = this.browserGamepad.buttons[13].value;
  61382. this.dPadRight = this.browserGamepad.buttons[14].value;
  61383. }
  61384. else {
  61385. this.buttonA = this.browserGamepad.buttons[0].value;
  61386. this.buttonB = this.browserGamepad.buttons[1].value;
  61387. this.buttonX = this.browserGamepad.buttons[2].value;
  61388. this.buttonY = this.browserGamepad.buttons[3].value;
  61389. this.buttonLB = this.browserGamepad.buttons[4].value;
  61390. this.buttonRB = this.browserGamepad.buttons[5].value;
  61391. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61392. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61393. this.buttonBack = this.browserGamepad.buttons[8].value;
  61394. this.buttonStart = this.browserGamepad.buttons[9].value;
  61395. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61396. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61397. this.dPadUp = this.browserGamepad.buttons[12].value;
  61398. this.dPadDown = this.browserGamepad.buttons[13].value;
  61399. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61400. this.dPadRight = this.browserGamepad.buttons[15].value;
  61401. }
  61402. };
  61403. Xbox360Pad.prototype.dispose = function () {
  61404. _super.prototype.dispose.call(this);
  61405. this.onButtonDownObservable.clear();
  61406. this.onButtonUpObservable.clear();
  61407. this.onPadDownObservable.clear();
  61408. this.onPadUpObservable.clear();
  61409. };
  61410. return Xbox360Pad;
  61411. }(BABYLON.Gamepad));
  61412. BABYLON.Xbox360Pad = Xbox360Pad;
  61413. })(BABYLON || (BABYLON = {}));
  61414. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61415. var BABYLON;
  61416. (function (BABYLON) {
  61417. var PoseEnabledControllerType;
  61418. (function (PoseEnabledControllerType) {
  61419. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61420. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61421. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61422. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61423. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61424. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61425. var PoseEnabledControllerHelper = /** @class */ (function () {
  61426. function PoseEnabledControllerHelper() {
  61427. }
  61428. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61429. // Oculus Touch
  61430. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61431. return new BABYLON.OculusTouchController(vrGamepad);
  61432. }
  61433. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61434. return new BABYLON.WindowsMotionController(vrGamepad);
  61435. }
  61436. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61437. return new BABYLON.ViveController(vrGamepad);
  61438. }
  61439. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61440. return new BABYLON.GearVRController(vrGamepad);
  61441. }
  61442. else {
  61443. return new BABYLON.GenericController(vrGamepad);
  61444. }
  61445. };
  61446. return PoseEnabledControllerHelper;
  61447. }());
  61448. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61449. var PoseEnabledController = /** @class */ (function (_super) {
  61450. __extends(PoseEnabledController, _super);
  61451. function PoseEnabledController(browserGamepad) {
  61452. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61453. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61454. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61455. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61456. // Represents device position and rotation in babylon space
  61457. _this.devicePosition = BABYLON.Vector3.Zero();
  61458. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61459. _this.deviceScaleFactor = 1;
  61460. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61461. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61462. _this._workingMatrix = BABYLON.Matrix.Identity();
  61463. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61464. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61465. _this.position = BABYLON.Vector3.Zero();
  61466. _this.rotationQuaternion = new BABYLON.Quaternion();
  61467. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61468. _this._calculatedRotation = new BABYLON.Quaternion();
  61469. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61470. return _this;
  61471. }
  61472. PoseEnabledController.prototype.update = function () {
  61473. _super.prototype.update.call(this);
  61474. var pose = this.browserGamepad.pose;
  61475. this.updateFromDevice(pose);
  61476. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61477. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61478. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61479. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61480. if (this._mesh) {
  61481. this._mesh.position.copyFrom(this.devicePosition);
  61482. if (this._mesh.rotationQuaternion) {
  61483. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61484. }
  61485. }
  61486. };
  61487. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61488. if (poseData) {
  61489. this.rawPose = poseData;
  61490. if (poseData.position) {
  61491. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61492. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61493. this._deviceRoomPosition.z *= -1;
  61494. }
  61495. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61496. this._calculatedPosition.addInPlace(this.position);
  61497. }
  61498. var pose = this.rawPose;
  61499. if (poseData.orientation && pose.orientation) {
  61500. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61501. if (this._mesh) {
  61502. if (this._mesh.getScene().useRightHandedSystem) {
  61503. this._deviceRoomRotationQuaternion.z *= -1;
  61504. this._deviceRoomRotationQuaternion.w *= -1;
  61505. }
  61506. else {
  61507. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61508. }
  61509. }
  61510. // if the camera is set, rotate to the camera's rotation
  61511. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61512. }
  61513. }
  61514. };
  61515. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61516. if (this._mesh) {
  61517. this._mesh.parent = null;
  61518. }
  61519. this._mesh = mesh;
  61520. if (this._poseControlledCamera) {
  61521. this._mesh.parent = this._poseControlledCamera;
  61522. }
  61523. if (!this._mesh.rotationQuaternion) {
  61524. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61525. }
  61526. };
  61527. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61528. this._poseControlledCamera = camera;
  61529. if (this._mesh) {
  61530. this._mesh.parent = this._poseControlledCamera;
  61531. }
  61532. };
  61533. PoseEnabledController.prototype.dispose = function () {
  61534. if (this._mesh) {
  61535. this._mesh.dispose();
  61536. }
  61537. this._mesh = null;
  61538. _super.prototype.dispose.call(this);
  61539. };
  61540. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61541. get: function () {
  61542. return this._mesh;
  61543. },
  61544. enumerable: true,
  61545. configurable: true
  61546. });
  61547. PoseEnabledController.prototype.getForwardRay = function (length) {
  61548. if (length === void 0) { length = 100; }
  61549. if (!this.mesh) {
  61550. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61551. }
  61552. var m = this.mesh.getWorldMatrix();
  61553. var origin = m.getTranslation();
  61554. var forward = new BABYLON.Vector3(0, 0, -1);
  61555. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61556. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61557. return new BABYLON.Ray(origin, direction, length);
  61558. };
  61559. return PoseEnabledController;
  61560. }(BABYLON.Gamepad));
  61561. BABYLON.PoseEnabledController = PoseEnabledController;
  61562. })(BABYLON || (BABYLON = {}));
  61563. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61564. var BABYLON;
  61565. (function (BABYLON) {
  61566. var WebVRController = /** @class */ (function (_super) {
  61567. __extends(WebVRController, _super);
  61568. function WebVRController(vrGamepad) {
  61569. var _this = _super.call(this, vrGamepad) || this;
  61570. // Observables
  61571. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61572. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61573. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61574. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61575. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61576. _this.pad = { x: 0, y: 0 };
  61577. // avoid GC, store state in a tmp object
  61578. _this._changes = {
  61579. pressChanged: false,
  61580. touchChanged: false,
  61581. valueChanged: false,
  61582. changed: false
  61583. };
  61584. _this._buttons = new Array(vrGamepad.buttons.length);
  61585. _this.hand = vrGamepad.hand;
  61586. return _this;
  61587. }
  61588. WebVRController.prototype.onButtonStateChange = function (callback) {
  61589. this._onButtonStateChange = callback;
  61590. };
  61591. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61592. get: function () {
  61593. return this._defaultModel;
  61594. },
  61595. enumerable: true,
  61596. configurable: true
  61597. });
  61598. WebVRController.prototype.update = function () {
  61599. _super.prototype.update.call(this);
  61600. for (var index = 0; index < this._buttons.length; index++) {
  61601. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61602. }
  61603. ;
  61604. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61605. this.pad.x = this.leftStick.x;
  61606. this.pad.y = this.leftStick.y;
  61607. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61608. }
  61609. };
  61610. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61611. if (!newState) {
  61612. newState = {
  61613. pressed: false,
  61614. touched: false,
  61615. value: 0
  61616. };
  61617. }
  61618. if (!currentState) {
  61619. this._buttons[buttonIndex] = {
  61620. pressed: newState.pressed,
  61621. touched: newState.touched,
  61622. value: newState.value
  61623. };
  61624. return;
  61625. }
  61626. this._checkChanges(newState, currentState);
  61627. if (this._changes.changed) {
  61628. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61629. this.handleButtonChange(buttonIndex, newState, this._changes);
  61630. }
  61631. this._buttons[buttonIndex].pressed = newState.pressed;
  61632. this._buttons[buttonIndex].touched = newState.touched;
  61633. // oculus triggers are never 0, thou not touched.
  61634. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61635. };
  61636. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61637. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61638. this._changes.touchChanged = newState.touched !== currentState.touched;
  61639. this._changes.valueChanged = newState.value !== currentState.value;
  61640. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61641. return this._changes;
  61642. };
  61643. WebVRController.prototype.dispose = function () {
  61644. _super.prototype.dispose.call(this);
  61645. this.onTriggerStateChangedObservable.clear();
  61646. this.onMainButtonStateChangedObservable.clear();
  61647. this.onSecondaryButtonStateChangedObservable.clear();
  61648. this.onPadStateChangedObservable.clear();
  61649. this.onPadValuesChangedObservable.clear();
  61650. };
  61651. return WebVRController;
  61652. }(BABYLON.PoseEnabledController));
  61653. BABYLON.WebVRController = WebVRController;
  61654. })(BABYLON || (BABYLON = {}));
  61655. //# sourceMappingURL=babylon.webVRController.js.map
  61656. var BABYLON;
  61657. (function (BABYLON) {
  61658. var OculusTouchController = /** @class */ (function (_super) {
  61659. __extends(OculusTouchController, _super);
  61660. function OculusTouchController(vrGamepad) {
  61661. var _this = _super.call(this, vrGamepad) || this;
  61662. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61663. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61664. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61665. return _this;
  61666. }
  61667. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61668. var _this = this;
  61669. var meshName;
  61670. // Hand
  61671. if (this.hand === 'left') {
  61672. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61673. }
  61674. else {
  61675. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61676. }
  61677. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61678. /*
  61679. Parent Mesh name: oculus_touch_left
  61680. - body
  61681. - trigger
  61682. - thumbstick
  61683. - grip
  61684. - button_y
  61685. - button_x
  61686. - button_enter
  61687. */
  61688. _this._defaultModel = newMeshes[1];
  61689. _this.attachToMesh(_this._defaultModel);
  61690. if (meshLoaded) {
  61691. meshLoaded(_this._defaultModel);
  61692. }
  61693. });
  61694. };
  61695. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61696. // helper getters for left and right hand.
  61697. get: function () {
  61698. if (this.hand === 'right') {
  61699. return this.onMainButtonStateChangedObservable;
  61700. }
  61701. else {
  61702. throw new Error('No A button on left hand');
  61703. }
  61704. },
  61705. enumerable: true,
  61706. configurable: true
  61707. });
  61708. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61709. get: function () {
  61710. if (this.hand === 'right') {
  61711. return this.onSecondaryButtonStateChangedObservable;
  61712. }
  61713. else {
  61714. throw new Error('No B button on left hand');
  61715. }
  61716. },
  61717. enumerable: true,
  61718. configurable: true
  61719. });
  61720. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61721. get: function () {
  61722. if (this.hand === 'left') {
  61723. return this.onMainButtonStateChangedObservable;
  61724. }
  61725. else {
  61726. throw new Error('No X button on right hand');
  61727. }
  61728. },
  61729. enumerable: true,
  61730. configurable: true
  61731. });
  61732. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61733. get: function () {
  61734. if (this.hand === 'left') {
  61735. return this.onSecondaryButtonStateChangedObservable;
  61736. }
  61737. else {
  61738. throw new Error('No Y button on right hand');
  61739. }
  61740. },
  61741. enumerable: true,
  61742. configurable: true
  61743. });
  61744. /*
  61745. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61746. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61747. 2) secondary trigger (same)
  61748. 3) A (right) X (left), touch, pressed = value
  61749. 4) B / Y
  61750. 5) thumb rest
  61751. */
  61752. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61753. var notifyObject = state; //{ state: state, changes: changes };
  61754. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61755. switch (buttonIdx) {
  61756. case 0:
  61757. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61758. return;
  61759. case 1:// index trigger
  61760. if (this._defaultModel) {
  61761. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61762. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61763. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61764. }
  61765. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61766. return;
  61767. case 2:// secondary trigger
  61768. if (this._defaultModel) {
  61769. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61770. }
  61771. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61772. return;
  61773. case 3:
  61774. if (this._defaultModel) {
  61775. if (notifyObject.pressed) {
  61776. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61777. }
  61778. else {
  61779. (this._defaultModel.getChildren()[1]).position.y = 0;
  61780. }
  61781. }
  61782. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61783. return;
  61784. case 4:
  61785. if (this._defaultModel) {
  61786. if (notifyObject.pressed) {
  61787. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61788. }
  61789. else {
  61790. (this._defaultModel.getChildren()[2]).position.y = 0;
  61791. }
  61792. }
  61793. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61794. return;
  61795. case 5:
  61796. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61797. return;
  61798. }
  61799. };
  61800. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61801. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61802. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61803. return OculusTouchController;
  61804. }(BABYLON.WebVRController));
  61805. BABYLON.OculusTouchController = OculusTouchController;
  61806. })(BABYLON || (BABYLON = {}));
  61807. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61808. var BABYLON;
  61809. (function (BABYLON) {
  61810. var ViveController = /** @class */ (function (_super) {
  61811. __extends(ViveController, _super);
  61812. function ViveController(vrGamepad) {
  61813. var _this = _super.call(this, vrGamepad) || this;
  61814. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  61815. _this._invertLeftStickY = true;
  61816. return _this;
  61817. }
  61818. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61819. var _this = this;
  61820. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  61821. /*
  61822. Parent Mesh name: ViveWand
  61823. - body
  61824. - r_gripper
  61825. - l_gripper
  61826. - menu_button
  61827. - system_button
  61828. - trackpad
  61829. - trigger
  61830. - LED
  61831. */
  61832. _this._defaultModel = newMeshes[1];
  61833. _this.attachToMesh(_this._defaultModel);
  61834. if (meshLoaded) {
  61835. meshLoaded(_this._defaultModel);
  61836. }
  61837. });
  61838. };
  61839. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  61840. get: function () {
  61841. return this.onMainButtonStateChangedObservable;
  61842. },
  61843. enumerable: true,
  61844. configurable: true
  61845. });
  61846. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  61847. get: function () {
  61848. return this.onMainButtonStateChangedObservable;
  61849. },
  61850. enumerable: true,
  61851. configurable: true
  61852. });
  61853. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  61854. get: function () {
  61855. return this.onSecondaryButtonStateChangedObservable;
  61856. },
  61857. enumerable: true,
  61858. configurable: true
  61859. });
  61860. /**
  61861. * Vive mapping:
  61862. * 0: touchpad
  61863. * 1: trigger
  61864. * 2: left AND right buttons
  61865. * 3: menu button
  61866. */
  61867. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61868. var notifyObject = state; //{ state: state, changes: changes };
  61869. switch (buttonIdx) {
  61870. case 0:
  61871. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61872. return;
  61873. case 1:// index trigger
  61874. if (this._defaultModel) {
  61875. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61876. }
  61877. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61878. return;
  61879. case 2:// left AND right button
  61880. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61881. return;
  61882. case 3:
  61883. if (this._defaultModel) {
  61884. if (notifyObject.pressed) {
  61885. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61886. }
  61887. else {
  61888. (this._defaultModel.getChildren()[2]).position.y = 0;
  61889. }
  61890. }
  61891. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61892. return;
  61893. }
  61894. };
  61895. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61896. ViveController.MODEL_FILENAME = 'wand.babylon';
  61897. return ViveController;
  61898. }(BABYLON.WebVRController));
  61899. BABYLON.ViveController = ViveController;
  61900. })(BABYLON || (BABYLON = {}));
  61901. //# sourceMappingURL=babylon.viveController.js.map
  61902. var BABYLON;
  61903. (function (BABYLON) {
  61904. var GenericController = /** @class */ (function (_super) {
  61905. __extends(GenericController, _super);
  61906. function GenericController(vrGamepad) {
  61907. return _super.call(this, vrGamepad) || this;
  61908. }
  61909. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61910. var _this = this;
  61911. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61912. _this._defaultModel = newMeshes[1];
  61913. _this.attachToMesh(_this._defaultModel);
  61914. if (meshLoaded) {
  61915. meshLoaded(_this._defaultModel);
  61916. }
  61917. });
  61918. };
  61919. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61920. console.log("Button id: " + buttonIdx + "state: ");
  61921. console.dir(state);
  61922. };
  61923. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61924. GenericController.MODEL_FILENAME = 'generic.babylon';
  61925. return GenericController;
  61926. }(BABYLON.WebVRController));
  61927. BABYLON.GenericController = GenericController;
  61928. })(BABYLON || (BABYLON = {}));
  61929. //# sourceMappingURL=babylon.genericController.js.map
  61930. var BABYLON;
  61931. (function (BABYLON) {
  61932. var LoadedMeshInfo = /** @class */ (function () {
  61933. function LoadedMeshInfo() {
  61934. this.buttonMeshes = {};
  61935. this.axisMeshes = {};
  61936. }
  61937. return LoadedMeshInfo;
  61938. }());
  61939. var WindowsMotionController = /** @class */ (function (_super) {
  61940. __extends(WindowsMotionController, _super);
  61941. function WindowsMotionController(vrGamepad) {
  61942. var _this = _super.call(this, vrGamepad) || this;
  61943. _this._mapping = {
  61944. // Semantic button names
  61945. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61946. // A mapping of the button name to glTF model node name
  61947. // that should be transformed by button value.
  61948. buttonMeshNames: {
  61949. 'trigger': 'SELECT',
  61950. 'menu': 'MENU',
  61951. 'grip': 'GRASP',
  61952. 'thumbstick': 'THUMBSTICK_PRESS',
  61953. 'trackpad': 'TOUCHPAD_PRESS'
  61954. },
  61955. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61956. buttonObservableNames: {
  61957. 'trigger': 'onTriggerStateChangedObservable',
  61958. 'menu': 'onSecondaryButtonStateChangedObservable',
  61959. 'grip': 'onMainButtonStateChangedObservable',
  61960. 'thumbstick': 'onPadStateChangedObservable',
  61961. 'trackpad': 'onTrackpadChangedObservable'
  61962. },
  61963. // A mapping of the axis name to glTF model node name
  61964. // that should be transformed by axis value.
  61965. // This array mirrors the browserGamepad.axes array, such that
  61966. // the mesh corresponding to axis 0 is in this array index 0.
  61967. axisMeshNames: [
  61968. 'THUMBSTICK_X',
  61969. 'THUMBSTICK_Y',
  61970. 'TOUCHPAD_TOUCH_X',
  61971. 'TOUCHPAD_TOUCH_Y'
  61972. ],
  61973. pointingPoseMeshName: 'POINTING_POSE'
  61974. };
  61975. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61976. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61977. _this.trackpad = { x: 0, y: 0 };
  61978. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61979. _this._loadedMeshInfo = null;
  61980. return _this;
  61981. }
  61982. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61983. get: function () {
  61984. return this.onTriggerStateChangedObservable;
  61985. },
  61986. enumerable: true,
  61987. configurable: true
  61988. });
  61989. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61990. get: function () {
  61991. return this.onSecondaryButtonStateChangedObservable;
  61992. },
  61993. enumerable: true,
  61994. configurable: true
  61995. });
  61996. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61997. get: function () {
  61998. return this.onMainButtonStateChangedObservable;
  61999. },
  62000. enumerable: true,
  62001. configurable: true
  62002. });
  62003. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  62004. get: function () {
  62005. return this.onPadStateChangedObservable;
  62006. },
  62007. enumerable: true,
  62008. configurable: true
  62009. });
  62010. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  62011. get: function () {
  62012. return this.onTrackpadChangedObservable;
  62013. },
  62014. enumerable: true,
  62015. configurable: true
  62016. });
  62017. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  62018. get: function () {
  62019. return this.onTrackpadValuesChangedObservable;
  62020. },
  62021. enumerable: true,
  62022. configurable: true
  62023. });
  62024. /**
  62025. * Called once per frame by the engine.
  62026. */
  62027. WindowsMotionController.prototype.update = function () {
  62028. _super.prototype.update.call(this);
  62029. // Only need to animate axes if there is a loaded mesh
  62030. if (this._loadedMeshInfo) {
  62031. if (this.browserGamepad.axes) {
  62032. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  62033. this.trackpad.x = this.browserGamepad["axes"][2];
  62034. this.trackpad.y = this.browserGamepad["axes"][3];
  62035. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  62036. }
  62037. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  62038. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  62039. }
  62040. }
  62041. }
  62042. };
  62043. /**
  62044. * Called once for each button that changed state since the last frame
  62045. * @param buttonIdx Which button index changed
  62046. * @param state New state of the button
  62047. * @param changes Which properties on the state changed since last frame
  62048. */
  62049. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62050. var buttonName = this._mapping.buttons[buttonIdx];
  62051. if (!buttonName) {
  62052. return;
  62053. }
  62054. // Only emit events for buttons that we know how to map from index to name
  62055. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  62056. if (observable) {
  62057. observable.notifyObservers(state);
  62058. }
  62059. this.lerpButtonTransform(buttonName, state.value);
  62060. };
  62061. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  62062. // If there is no loaded mesh, there is nothing to transform.
  62063. if (!this._loadedMeshInfo) {
  62064. return;
  62065. }
  62066. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  62067. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  62068. return;
  62069. }
  62070. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  62071. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  62072. };
  62073. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  62074. if (!this._loadedMeshInfo) {
  62075. return;
  62076. }
  62077. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  62078. if (!meshInfo) {
  62079. return;
  62080. }
  62081. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  62082. return;
  62083. }
  62084. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  62085. var lerpValue = axisValue * 0.5 + 0.5;
  62086. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  62087. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  62088. };
  62089. /**
  62090. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  62091. * @param scene scene in which to add meshes
  62092. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  62093. */
  62094. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  62095. var _this = this;
  62096. if (forceDefault === void 0) { forceDefault = false; }
  62097. var path;
  62098. var filename;
  62099. // Checking if GLB loader is present
  62100. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  62101. // Determine the device specific folder based on the ID suffix
  62102. var device = 'default';
  62103. if (this.id && !forceDefault) {
  62104. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  62105. device = ((match && match[0]) || device);
  62106. }
  62107. // Hand
  62108. if (this.hand === 'left') {
  62109. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  62110. }
  62111. else {
  62112. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  62113. }
  62114. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  62115. }
  62116. else {
  62117. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  62118. path = BABYLON.GenericController.MODEL_BASE_URL;
  62119. filename = BABYLON.GenericController.MODEL_FILENAME;
  62120. }
  62121. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  62122. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  62123. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  62124. if (!_this._loadedMeshInfo) {
  62125. return;
  62126. }
  62127. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  62128. _this.attachToMesh(_this._defaultModel);
  62129. if (meshLoaded) {
  62130. meshLoaded(_this._defaultModel);
  62131. }
  62132. }, null, function (scene, message) {
  62133. BABYLON.Tools.Log(message);
  62134. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  62135. if (!forceDefault) {
  62136. _this.initControllerMesh(scene, meshLoaded, true);
  62137. }
  62138. });
  62139. };
  62140. /**
  62141. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  62142. * can be transformed by button presses and axes values, based on this._mapping.
  62143. *
  62144. * @param scene scene in which the meshes exist
  62145. * @param meshes list of meshes that make up the controller model to process
  62146. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  62147. */
  62148. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  62149. var loadedMeshInfo = null;
  62150. // Create a new mesh to contain the glTF hierarchy
  62151. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  62152. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  62153. var childMesh = null;
  62154. for (var i = 0; i < meshes.length; i++) {
  62155. var mesh = meshes[i];
  62156. if (!mesh.parent) {
  62157. // Exclude controller meshes from picking results
  62158. mesh.isPickable = false;
  62159. // Handle root node, attach to the new parentMesh
  62160. childMesh = mesh;
  62161. break;
  62162. }
  62163. }
  62164. if (childMesh) {
  62165. childMesh.setParent(parentMesh);
  62166. // Create our mesh info. Note that this method will always return non-null.
  62167. loadedMeshInfo = this.createMeshInfo(parentMesh);
  62168. }
  62169. else {
  62170. BABYLON.Tools.Warn('Could not find root node in model file.');
  62171. }
  62172. return loadedMeshInfo;
  62173. };
  62174. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  62175. var loadedMeshInfo = new LoadedMeshInfo();
  62176. var i;
  62177. loadedMeshInfo.rootNode = rootNode;
  62178. // Reset the caches
  62179. loadedMeshInfo.buttonMeshes = {};
  62180. loadedMeshInfo.axisMeshes = {};
  62181. // Button Meshes
  62182. for (i = 0; i < this._mapping.buttons.length; i++) {
  62183. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  62184. if (!buttonMeshName) {
  62185. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  62186. continue;
  62187. }
  62188. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  62189. if (!buttonMesh) {
  62190. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  62191. continue;
  62192. }
  62193. var buttonMeshInfo = {
  62194. index: i,
  62195. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  62196. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  62197. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  62198. };
  62199. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  62200. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  62201. }
  62202. else {
  62203. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  62204. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  62205. '(VALUE: ' + !!buttonMeshInfo.value +
  62206. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  62207. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  62208. ')');
  62209. }
  62210. }
  62211. // Axis Meshes
  62212. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  62213. var axisMeshName = this._mapping.axisMeshNames[i];
  62214. if (!axisMeshName) {
  62215. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  62216. continue;
  62217. }
  62218. var axisMesh = getChildByName(rootNode, axisMeshName);
  62219. if (!axisMesh) {
  62220. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  62221. continue;
  62222. }
  62223. var axisMeshInfo = {
  62224. index: i,
  62225. value: getImmediateChildByName(axisMesh, 'VALUE'),
  62226. min: getImmediateChildByName(axisMesh, 'MIN'),
  62227. max: getImmediateChildByName(axisMesh, 'MAX')
  62228. };
  62229. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  62230. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  62231. }
  62232. else {
  62233. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  62234. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  62235. '(VALUE: ' + !!axisMeshInfo.value +
  62236. ', MIN: ' + !!axisMeshInfo.min +
  62237. ', MAX:' + !!axisMeshInfo.max +
  62238. ')');
  62239. }
  62240. }
  62241. // Pointing Ray
  62242. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  62243. if (!loadedMeshInfo.pointingPoseNode) {
  62244. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  62245. }
  62246. return loadedMeshInfo;
  62247. // Look through all children recursively. This will return null if no mesh exists with the given name.
  62248. function getChildByName(node, name) {
  62249. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  62250. }
  62251. // Look through only immediate children. This will return null if no mesh exists with the given name.
  62252. function getImmediateChildByName(node, name) {
  62253. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  62254. }
  62255. };
  62256. WindowsMotionController.prototype.getForwardRay = function (length) {
  62257. if (length === void 0) { length = 100; }
  62258. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  62259. return _super.prototype.getForwardRay.call(this, length);
  62260. }
  62261. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  62262. var origin = m.getTranslation();
  62263. var forward = new BABYLON.Vector3(0, 0, -1);
  62264. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  62265. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  62266. return new BABYLON.Ray(origin, direction, length);
  62267. };
  62268. WindowsMotionController.prototype.dispose = function () {
  62269. _super.prototype.dispose.call(this);
  62270. this.onTrackpadChangedObservable.clear();
  62271. };
  62272. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  62273. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  62274. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  62275. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  62276. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  62277. return WindowsMotionController;
  62278. }(BABYLON.WebVRController));
  62279. BABYLON.WindowsMotionController = WindowsMotionController;
  62280. })(BABYLON || (BABYLON = {}));
  62281. //# sourceMappingURL=babylon.windowsMotionController.js.map
  62282. var BABYLON;
  62283. (function (BABYLON) {
  62284. var GearVRController = /** @class */ (function (_super) {
  62285. __extends(GearVRController, _super);
  62286. function GearVRController(vrGamepad) {
  62287. var _this = _super.call(this, vrGamepad) || this;
  62288. _this._buttonIndexToObservableNameMap = [
  62289. 'onTrackpadChangedObservable',
  62290. 'onTriggerStateChangedObservable' // Trigger
  62291. ];
  62292. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  62293. return _this;
  62294. }
  62295. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62296. var _this = this;
  62297. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  62298. _this._defaultModel = newMeshes[1];
  62299. _this.attachToMesh(_this._defaultModel);
  62300. if (meshLoaded) {
  62301. meshLoaded(_this._defaultModel);
  62302. }
  62303. });
  62304. };
  62305. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62306. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  62307. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  62308. // Only emit events for buttons that we know how to map from index to observable
  62309. var observable = this[observableName];
  62310. if (observable) {
  62311. observable.notifyObservers(state);
  62312. }
  62313. }
  62314. };
  62315. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  62316. GearVRController.MODEL_FILENAME = 'generic.babylon';
  62317. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  62318. return GearVRController;
  62319. }(BABYLON.WebVRController));
  62320. BABYLON.GearVRController = GearVRController;
  62321. })(BABYLON || (BABYLON = {}));
  62322. //# sourceMappingURL=babylon.gearVRController.js.map
  62323. var BABYLON;
  62324. (function (BABYLON) {
  62325. var FollowCamera = /** @class */ (function (_super) {
  62326. __extends(FollowCamera, _super);
  62327. function FollowCamera(name, position, scene, lockedTarget) {
  62328. if (lockedTarget === void 0) { lockedTarget = null; }
  62329. var _this = _super.call(this, name, position, scene) || this;
  62330. _this.radius = 12;
  62331. _this.rotationOffset = 0;
  62332. _this.heightOffset = 4;
  62333. _this.cameraAcceleration = 0.05;
  62334. _this.maxCameraSpeed = 20;
  62335. _this.lockedTarget = lockedTarget;
  62336. return _this;
  62337. }
  62338. FollowCamera.prototype.getRadians = function (degrees) {
  62339. return degrees * Math.PI / 180;
  62340. };
  62341. FollowCamera.prototype.follow = function (cameraTarget) {
  62342. if (!cameraTarget)
  62343. return;
  62344. var yRotation;
  62345. if (cameraTarget.rotationQuaternion) {
  62346. var rotMatrix = new BABYLON.Matrix();
  62347. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  62348. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  62349. }
  62350. else {
  62351. yRotation = cameraTarget.rotation.y;
  62352. }
  62353. var radians = this.getRadians(this.rotationOffset) + yRotation;
  62354. var targetPosition = cameraTarget.getAbsolutePosition();
  62355. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  62356. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  62357. var dx = targetX - this.position.x;
  62358. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  62359. var dz = (targetZ) - this.position.z;
  62360. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  62361. var vy = dy * this.cameraAcceleration;
  62362. var vz = dz * this.cameraAcceleration * 2;
  62363. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  62364. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62365. }
  62366. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  62367. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62368. }
  62369. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  62370. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62371. }
  62372. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  62373. this.setTarget(targetPosition);
  62374. };
  62375. FollowCamera.prototype._checkInputs = function () {
  62376. _super.prototype._checkInputs.call(this);
  62377. if (this.lockedTarget) {
  62378. this.follow(this.lockedTarget);
  62379. }
  62380. };
  62381. FollowCamera.prototype.getClassName = function () {
  62382. return "FollowCamera";
  62383. };
  62384. __decorate([
  62385. BABYLON.serialize()
  62386. ], FollowCamera.prototype, "radius", void 0);
  62387. __decorate([
  62388. BABYLON.serialize()
  62389. ], FollowCamera.prototype, "rotationOffset", void 0);
  62390. __decorate([
  62391. BABYLON.serialize()
  62392. ], FollowCamera.prototype, "heightOffset", void 0);
  62393. __decorate([
  62394. BABYLON.serialize()
  62395. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62396. __decorate([
  62397. BABYLON.serialize()
  62398. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62399. __decorate([
  62400. BABYLON.serializeAsMeshReference("lockedTargetId")
  62401. ], FollowCamera.prototype, "lockedTarget", void 0);
  62402. return FollowCamera;
  62403. }(BABYLON.TargetCamera));
  62404. BABYLON.FollowCamera = FollowCamera;
  62405. var ArcFollowCamera = /** @class */ (function (_super) {
  62406. __extends(ArcFollowCamera, _super);
  62407. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62408. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62409. _this.alpha = alpha;
  62410. _this.beta = beta;
  62411. _this.radius = radius;
  62412. _this.target = target;
  62413. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62414. _this.follow();
  62415. return _this;
  62416. }
  62417. ArcFollowCamera.prototype.follow = function () {
  62418. if (!this.target) {
  62419. return;
  62420. }
  62421. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62422. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62423. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62424. var targetPosition = this.target.getAbsolutePosition();
  62425. this.position = targetPosition.add(this._cartesianCoordinates);
  62426. this.setTarget(targetPosition);
  62427. };
  62428. ArcFollowCamera.prototype._checkInputs = function () {
  62429. _super.prototype._checkInputs.call(this);
  62430. this.follow();
  62431. };
  62432. ArcFollowCamera.prototype.getClassName = function () {
  62433. return "ArcFollowCamera";
  62434. };
  62435. return ArcFollowCamera;
  62436. }(BABYLON.TargetCamera));
  62437. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62438. })(BABYLON || (BABYLON = {}));
  62439. //# sourceMappingURL=babylon.followCamera.js.map
  62440. var BABYLON;
  62441. (function (BABYLON) {
  62442. // We're mainly based on the logic defined into the FreeCamera code
  62443. var UniversalCamera = /** @class */ (function (_super) {
  62444. __extends(UniversalCamera, _super);
  62445. //-- end properties for backward compatibility for inputs
  62446. function UniversalCamera(name, position, scene) {
  62447. var _this = _super.call(this, name, position, scene) || this;
  62448. _this.inputs.addGamepad();
  62449. return _this;
  62450. }
  62451. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62452. //-- Begin properties for backward compatibility for inputs
  62453. get: function () {
  62454. var gamepad = this.inputs.attached["gamepad"];
  62455. if (gamepad)
  62456. return gamepad.gamepadAngularSensibility;
  62457. return 0;
  62458. },
  62459. set: function (value) {
  62460. var gamepad = this.inputs.attached["gamepad"];
  62461. if (gamepad)
  62462. gamepad.gamepadAngularSensibility = value;
  62463. },
  62464. enumerable: true,
  62465. configurable: true
  62466. });
  62467. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62468. get: function () {
  62469. var gamepad = this.inputs.attached["gamepad"];
  62470. if (gamepad)
  62471. return gamepad.gamepadMoveSensibility;
  62472. return 0;
  62473. },
  62474. set: function (value) {
  62475. var gamepad = this.inputs.attached["gamepad"];
  62476. if (gamepad)
  62477. gamepad.gamepadMoveSensibility = value;
  62478. },
  62479. enumerable: true,
  62480. configurable: true
  62481. });
  62482. UniversalCamera.prototype.getClassName = function () {
  62483. return "UniversalCamera";
  62484. };
  62485. return UniversalCamera;
  62486. }(BABYLON.TouchCamera));
  62487. BABYLON.UniversalCamera = UniversalCamera;
  62488. })(BABYLON || (BABYLON = {}));
  62489. //# sourceMappingURL=babylon.universalCamera.js.map
  62490. var BABYLON;
  62491. (function (BABYLON) {
  62492. // We're mainly based on the logic defined into the FreeCamera code
  62493. var GamepadCamera = /** @class */ (function (_super) {
  62494. __extends(GamepadCamera, _super);
  62495. //-- end properties for backward compatibility for inputs
  62496. function GamepadCamera(name, position, scene) {
  62497. return _super.call(this, name, position, scene) || this;
  62498. }
  62499. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62500. //-- Begin properties for backward compatibility for inputs
  62501. get: function () {
  62502. var gamepad = this.inputs.attached["gamepad"];
  62503. if (gamepad)
  62504. return gamepad.gamepadAngularSensibility;
  62505. return 0;
  62506. },
  62507. set: function (value) {
  62508. var gamepad = this.inputs.attached["gamepad"];
  62509. if (gamepad)
  62510. gamepad.gamepadAngularSensibility = value;
  62511. },
  62512. enumerable: true,
  62513. configurable: true
  62514. });
  62515. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62516. get: function () {
  62517. var gamepad = this.inputs.attached["gamepad"];
  62518. if (gamepad)
  62519. return gamepad.gamepadMoveSensibility;
  62520. return 0;
  62521. },
  62522. set: function (value) {
  62523. var gamepad = this.inputs.attached["gamepad"];
  62524. if (gamepad)
  62525. gamepad.gamepadMoveSensibility = value;
  62526. },
  62527. enumerable: true,
  62528. configurable: true
  62529. });
  62530. GamepadCamera.prototype.getClassName = function () {
  62531. return "GamepadCamera";
  62532. };
  62533. return GamepadCamera;
  62534. }(BABYLON.UniversalCamera));
  62535. BABYLON.GamepadCamera = GamepadCamera;
  62536. })(BABYLON || (BABYLON = {}));
  62537. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62538. var BABYLON;
  62539. (function (BABYLON) {
  62540. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62541. function PostProcessRenderPipelineManager() {
  62542. this._renderPipelines = {};
  62543. }
  62544. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62545. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62546. };
  62547. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62548. if (unique === void 0) { unique = false; }
  62549. var renderPipeline = this._renderPipelines[renderPipelineName];
  62550. if (!renderPipeline) {
  62551. return;
  62552. }
  62553. renderPipeline._attachCameras(cameras, unique);
  62554. };
  62555. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62556. var renderPipeline = this._renderPipelines[renderPipelineName];
  62557. if (!renderPipeline) {
  62558. return;
  62559. }
  62560. renderPipeline._detachCameras(cameras);
  62561. };
  62562. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62563. var renderPipeline = this._renderPipelines[renderPipelineName];
  62564. if (!renderPipeline) {
  62565. return;
  62566. }
  62567. renderPipeline._enableEffect(renderEffectName, cameras);
  62568. };
  62569. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62570. var renderPipeline = this._renderPipelines[renderPipelineName];
  62571. if (!renderPipeline) {
  62572. return;
  62573. }
  62574. renderPipeline._disableEffect(renderEffectName, cameras);
  62575. };
  62576. PostProcessRenderPipelineManager.prototype.update = function () {
  62577. for (var renderPipelineName in this._renderPipelines) {
  62578. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62579. var pipeline = this._renderPipelines[renderPipelineName];
  62580. if (!pipeline.isSupported) {
  62581. pipeline.dispose();
  62582. delete this._renderPipelines[renderPipelineName];
  62583. }
  62584. else {
  62585. pipeline._update();
  62586. }
  62587. }
  62588. }
  62589. };
  62590. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62591. for (var renderPipelineName in this._renderPipelines) {
  62592. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62593. var pipeline = this._renderPipelines[renderPipelineName];
  62594. pipeline._rebuild();
  62595. }
  62596. }
  62597. };
  62598. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62599. for (var renderPipelineName in this._renderPipelines) {
  62600. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62601. var pipeline = this._renderPipelines[renderPipelineName];
  62602. pipeline.dispose();
  62603. }
  62604. }
  62605. };
  62606. return PostProcessRenderPipelineManager;
  62607. }());
  62608. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62609. })(BABYLON || (BABYLON = {}));
  62610. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62611. var BABYLON;
  62612. (function (BABYLON) {
  62613. /**
  62614. * This represents a set of one or more post processes in Babylon.
  62615. * A post process can be used to apply a shader to a texture after it is rendered.
  62616. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62617. */
  62618. var PostProcessRenderEffect = /** @class */ (function () {
  62619. /**
  62620. * Instantiates a post process render effect.
  62621. * A post process can be used to apply a shader to a texture after it is rendered.
  62622. * @param engine The engine the effect is tied to
  62623. * @param name The name of the effect
  62624. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62625. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62626. */
  62627. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62628. this._name = name;
  62629. this._singleInstance = singleInstance || true;
  62630. this._getPostProcesses = getPostProcesses;
  62631. this._cameras = {};
  62632. this._indicesForCamera = {};
  62633. this._postProcesses = {};
  62634. }
  62635. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62636. /**
  62637. * Checks if all the post processes in the effect are supported.
  62638. */
  62639. get: function () {
  62640. for (var index in this._postProcesses) {
  62641. for (var ppIndex in this._postProcesses[index]) {
  62642. if (!this._postProcesses[index][ppIndex].isSupported) {
  62643. return false;
  62644. }
  62645. }
  62646. }
  62647. return true;
  62648. },
  62649. enumerable: true,
  62650. configurable: true
  62651. });
  62652. /**
  62653. * Updates the current state of the effect
  62654. */
  62655. PostProcessRenderEffect.prototype._update = function () {
  62656. };
  62657. /**
  62658. * Attaches the effect on cameras
  62659. * @param cameras The camera to attach to.
  62660. */
  62661. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62662. var _this = this;
  62663. var cameraKey;
  62664. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62665. if (!cams) {
  62666. return;
  62667. }
  62668. for (var i = 0; i < cams.length; i++) {
  62669. var camera = cams[i];
  62670. var cameraName = camera.name;
  62671. if (this._singleInstance) {
  62672. cameraKey = 0;
  62673. }
  62674. else {
  62675. cameraKey = cameraName;
  62676. }
  62677. if (!this._postProcesses[cameraKey]) {
  62678. var postProcess = this._getPostProcesses();
  62679. if (postProcess) {
  62680. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62681. }
  62682. }
  62683. if (!this._indicesForCamera[cameraName]) {
  62684. this._indicesForCamera[cameraName] = [];
  62685. }
  62686. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62687. var index = camera.attachPostProcess(postProcess);
  62688. _this._indicesForCamera[cameraName].push(index);
  62689. });
  62690. if (!this._cameras[cameraName]) {
  62691. this._cameras[cameraName] = camera;
  62692. }
  62693. }
  62694. };
  62695. /**
  62696. * Detatches the effect on cameras
  62697. * @param cameras The camera to detatch from.
  62698. */
  62699. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62700. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62701. if (!cams) {
  62702. return;
  62703. }
  62704. for (var i = 0; i < cams.length; i++) {
  62705. var camera = cams[i];
  62706. var cameraName = camera.name;
  62707. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62708. camera.detachPostProcess(postProcess);
  62709. });
  62710. if (this._cameras[cameraName]) {
  62711. //this._indicesForCamera.splice(index, 1);
  62712. this._cameras[cameraName] = null;
  62713. }
  62714. }
  62715. };
  62716. /**
  62717. * Enables the effect on given cameras
  62718. * @param cameras The camera to enable.
  62719. */
  62720. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62721. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62722. if (!cams) {
  62723. return;
  62724. }
  62725. for (var i = 0; i < cams.length; i++) {
  62726. var camera = cams[i];
  62727. var cameraName = camera.name;
  62728. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62729. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62730. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62731. }
  62732. }
  62733. }
  62734. };
  62735. /**
  62736. * Disables the effect on the given cameras
  62737. * @param cameras The camera to disable.
  62738. */
  62739. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62740. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62741. if (!cams) {
  62742. return;
  62743. }
  62744. for (var i = 0; i < cams.length; i++) {
  62745. var camera = cams[i];
  62746. var cameraName = camera.Name;
  62747. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62748. }
  62749. };
  62750. /**
  62751. * Gets a list of the post processes contained in the effect.
  62752. * @param camera The camera to get the post processes on.
  62753. * @returns The list of the post processes in the effect.
  62754. */
  62755. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62756. if (this._singleInstance) {
  62757. return this._postProcesses[0];
  62758. }
  62759. else {
  62760. if (!camera) {
  62761. return null;
  62762. }
  62763. return this._postProcesses[camera.name];
  62764. }
  62765. };
  62766. return PostProcessRenderEffect;
  62767. }());
  62768. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62769. })(BABYLON || (BABYLON = {}));
  62770. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62771. var BABYLON;
  62772. (function (BABYLON) {
  62773. var PostProcessRenderPipeline = /** @class */ (function () {
  62774. function PostProcessRenderPipeline(engine, name) {
  62775. this._name = name;
  62776. this._renderEffects = {};
  62777. this._renderEffectsForIsolatedPass = new Array();
  62778. this._cameras = [];
  62779. }
  62780. PostProcessRenderPipeline.prototype.getClassName = function () {
  62781. return "PostProcessRenderPipeline";
  62782. };
  62783. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62784. get: function () {
  62785. for (var renderEffectName in this._renderEffects) {
  62786. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62787. if (!this._renderEffects[renderEffectName].isSupported) {
  62788. return false;
  62789. }
  62790. }
  62791. }
  62792. return true;
  62793. },
  62794. enumerable: true,
  62795. configurable: true
  62796. });
  62797. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62798. this._renderEffects[renderEffect._name] = renderEffect;
  62799. };
  62800. // private
  62801. PostProcessRenderPipeline.prototype._rebuild = function () {
  62802. };
  62803. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62804. var renderEffects = this._renderEffects[renderEffectName];
  62805. if (!renderEffects) {
  62806. return;
  62807. }
  62808. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62809. };
  62810. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62811. var renderEffects = this._renderEffects[renderEffectName];
  62812. if (!renderEffects) {
  62813. return;
  62814. }
  62815. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62816. };
  62817. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62818. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62819. if (!cams) {
  62820. return;
  62821. }
  62822. var indicesToDelete = [];
  62823. var i;
  62824. for (i = 0; i < cams.length; i++) {
  62825. var camera = cams[i];
  62826. var cameraName = camera.name;
  62827. if (this._cameras.indexOf(camera) === -1) {
  62828. this._cameras[cameraName] = camera;
  62829. }
  62830. else if (unique) {
  62831. indicesToDelete.push(i);
  62832. }
  62833. }
  62834. for (i = 0; i < indicesToDelete.length; i++) {
  62835. cameras.splice(indicesToDelete[i], 1);
  62836. }
  62837. for (var renderEffectName in this._renderEffects) {
  62838. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62839. this._renderEffects[renderEffectName]._attachCameras(cams);
  62840. }
  62841. }
  62842. };
  62843. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62844. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62845. if (!cams) {
  62846. return;
  62847. }
  62848. for (var renderEffectName in this._renderEffects) {
  62849. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62850. this._renderEffects[renderEffectName]._detachCameras(cams);
  62851. }
  62852. }
  62853. for (var i = 0; i < cams.length; i++) {
  62854. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62855. }
  62856. };
  62857. PostProcessRenderPipeline.prototype._update = function () {
  62858. for (var renderEffectName in this._renderEffects) {
  62859. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62860. this._renderEffects[renderEffectName]._update();
  62861. }
  62862. }
  62863. for (var i = 0; i < this._cameras.length; i++) {
  62864. var cameraName = this._cameras[i].name;
  62865. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62866. this._renderEffectsForIsolatedPass[cameraName]._update();
  62867. }
  62868. }
  62869. };
  62870. PostProcessRenderPipeline.prototype._reset = function () {
  62871. this._renderEffects = {};
  62872. this._renderEffectsForIsolatedPass = new Array();
  62873. };
  62874. PostProcessRenderPipeline.prototype.dispose = function () {
  62875. // Must be implemented by children
  62876. };
  62877. __decorate([
  62878. BABYLON.serialize()
  62879. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62880. return PostProcessRenderPipeline;
  62881. }());
  62882. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62883. })(BABYLON || (BABYLON = {}));
  62884. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62885. var BABYLON;
  62886. (function (BABYLON) {
  62887. var DepthRenderer = /** @class */ (function () {
  62888. function DepthRenderer(scene, type) {
  62889. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62890. var _this = this;
  62891. this._scene = scene;
  62892. var engine = scene.getEngine();
  62893. // Render target
  62894. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62895. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62896. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62897. this._depthMap.refreshRate = 1;
  62898. this._depthMap.renderParticles = false;
  62899. this._depthMap.renderList = null;
  62900. // set default depth value to 1.0 (far away)
  62901. this._depthMap.onClearObservable.add(function (engine) {
  62902. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62903. });
  62904. // Custom render function
  62905. var renderSubMesh = function (subMesh) {
  62906. var mesh = subMesh.getRenderingMesh();
  62907. var scene = _this._scene;
  62908. var engine = scene.getEngine();
  62909. var material = subMesh.getMaterial();
  62910. if (!material) {
  62911. return;
  62912. }
  62913. // Culling and reverse (right handed system)
  62914. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62915. // Managing instances
  62916. var batch = mesh._getInstancesRenderList(subMesh._id);
  62917. if (batch.mustReturn) {
  62918. return;
  62919. }
  62920. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62921. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62922. engine.enableEffect(_this._effect);
  62923. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62924. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62925. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62926. // Alpha test
  62927. if (material && material.needAlphaTesting()) {
  62928. var alphaTexture = material.getAlphaTestTexture();
  62929. if (alphaTexture) {
  62930. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62931. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62932. }
  62933. }
  62934. // Bones
  62935. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62936. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62937. }
  62938. // Draw
  62939. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62940. }
  62941. };
  62942. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62943. var index;
  62944. if (depthOnlySubMeshes.length) {
  62945. engine.setColorWrite(false);
  62946. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62947. renderSubMesh(depthOnlySubMeshes.data[index]);
  62948. }
  62949. engine.setColorWrite(true);
  62950. }
  62951. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62952. renderSubMesh(opaqueSubMeshes.data[index]);
  62953. }
  62954. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62955. renderSubMesh(alphaTestSubMeshes.data[index]);
  62956. }
  62957. };
  62958. }
  62959. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62960. var material = subMesh.getMaterial();
  62961. if (material.disableDepthWrite) {
  62962. return false;
  62963. }
  62964. var defines = [];
  62965. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62966. var mesh = subMesh.getMesh();
  62967. // Alpha test
  62968. if (material && material.needAlphaTesting()) {
  62969. defines.push("#define ALPHATEST");
  62970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62971. attribs.push(BABYLON.VertexBuffer.UVKind);
  62972. defines.push("#define UV1");
  62973. }
  62974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62976. defines.push("#define UV2");
  62977. }
  62978. }
  62979. // Bones
  62980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62981. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62982. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62983. if (mesh.numBoneInfluencers > 4) {
  62984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62986. }
  62987. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62988. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62989. }
  62990. else {
  62991. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62992. }
  62993. // Instances
  62994. if (useInstances) {
  62995. defines.push("#define INSTANCES");
  62996. attribs.push("world0");
  62997. attribs.push("world1");
  62998. attribs.push("world2");
  62999. attribs.push("world3");
  63000. }
  63001. // Get correct effect
  63002. var join = defines.join("\n");
  63003. if (this._cachedDefines !== join) {
  63004. this._cachedDefines = join;
  63005. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  63006. }
  63007. return this._effect.isReady();
  63008. };
  63009. DepthRenderer.prototype.getDepthMap = function () {
  63010. return this._depthMap;
  63011. };
  63012. // Methods
  63013. DepthRenderer.prototype.dispose = function () {
  63014. this._depthMap.dispose();
  63015. };
  63016. return DepthRenderer;
  63017. }());
  63018. BABYLON.DepthRenderer = DepthRenderer;
  63019. })(BABYLON || (BABYLON = {}));
  63020. //# sourceMappingURL=babylon.depthRenderer.js.map
  63021. var BABYLON;
  63022. (function (BABYLON) {
  63023. var SSAORenderingPipeline = /** @class */ (function (_super) {
  63024. __extends(SSAORenderingPipeline, _super);
  63025. /**
  63026. * @constructor
  63027. * @param {string} name - The rendering pipeline name
  63028. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63029. * @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 }
  63030. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63031. */
  63032. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  63033. var _this = _super.call(this, scene.getEngine(), name) || this;
  63034. // Members
  63035. /**
  63036. * The PassPostProcess id in the pipeline that contains the original scene color
  63037. * @type {string}
  63038. */
  63039. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63040. /**
  63041. * The SSAO PostProcess id in the pipeline
  63042. * @type {string}
  63043. */
  63044. _this.SSAORenderEffect = "SSAORenderEffect";
  63045. /**
  63046. * The horizontal blur PostProcess id in the pipeline
  63047. * @type {string}
  63048. */
  63049. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63050. /**
  63051. * The vertical blur PostProcess id in the pipeline
  63052. * @type {string}
  63053. */
  63054. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63055. /**
  63056. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63057. * @type {string}
  63058. */
  63059. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63060. /**
  63061. * The output strength of the SSAO post-process. Default value is 1.0.
  63062. * @type {number}
  63063. */
  63064. _this.totalStrength = 1.0;
  63065. /**
  63066. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  63067. * @type {number}
  63068. */
  63069. _this.radius = 0.0001;
  63070. /**
  63071. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  63072. * Must not be equal to fallOff and superior to fallOff.
  63073. * Default value is 0.975
  63074. * @type {number}
  63075. */
  63076. _this.area = 0.0075;
  63077. /**
  63078. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  63079. * Must not be equal to area and inferior to area.
  63080. * Default value is 0.0
  63081. * @type {number}
  63082. */
  63083. _this.fallOff = 0.000001;
  63084. /**
  63085. * The base color of the SSAO post-process
  63086. * The final result is "base + ssao" between [0, 1]
  63087. * @type {number}
  63088. */
  63089. _this.base = 0.5;
  63090. _this._firstUpdate = true;
  63091. _this._scene = scene;
  63092. // Set up assets
  63093. _this._createRandomTexture();
  63094. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63095. var ssaoRatio = ratio.ssaoRatio || ratio;
  63096. var combineRatio = ratio.combineRatio || ratio;
  63097. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63098. _this._createSSAOPostProcess(ssaoRatio);
  63099. _this._createBlurPostProcess(ssaoRatio);
  63100. _this._createSSAOCombinePostProcess(combineRatio);
  63101. // Set up pipeline
  63102. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63103. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63104. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63105. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63107. // Finish
  63108. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63109. if (cameras)
  63110. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63111. return _this;
  63112. }
  63113. // Public Methods
  63114. /**
  63115. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63116. */
  63117. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63118. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63119. for (var i = 0; i < this._scene.cameras.length; i++) {
  63120. var camera = this._scene.cameras[i];
  63121. this._originalColorPostProcess.dispose(camera);
  63122. this._ssaoPostProcess.dispose(camera);
  63123. this._blurHPostProcess.dispose(camera);
  63124. this._blurVPostProcess.dispose(camera);
  63125. this._ssaoCombinePostProcess.dispose(camera);
  63126. }
  63127. this._randomTexture.dispose();
  63128. if (disableDepthRender)
  63129. this._scene.disableDepthRenderer();
  63130. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63131. _super.prototype.dispose.call(this);
  63132. };
  63133. // Private Methods
  63134. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  63135. var _this = this;
  63136. var size = 16;
  63137. 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);
  63138. 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);
  63139. this._blurHPostProcess.onActivateObservable.add(function () {
  63140. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  63141. _this._blurHPostProcess.kernel = size * dw;
  63142. });
  63143. this._blurVPostProcess.onActivateObservable.add(function () {
  63144. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  63145. _this._blurVPostProcess.kernel = size * dw;
  63146. });
  63147. };
  63148. SSAORenderingPipeline.prototype._rebuild = function () {
  63149. this._firstUpdate = true;
  63150. _super.prototype._rebuild.call(this);
  63151. };
  63152. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63153. var _this = this;
  63154. var numSamples = 16;
  63155. var sampleSphere = [
  63156. 0.5381, 0.1856, -0.4319,
  63157. 0.1379, 0.2486, 0.4430,
  63158. 0.3371, 0.5679, -0.0057,
  63159. -0.6999, -0.0451, -0.0019,
  63160. 0.0689, -0.1598, -0.8547,
  63161. 0.0560, 0.0069, -0.1843,
  63162. -0.0146, 0.1402, 0.0762,
  63163. 0.0100, -0.1924, -0.0344,
  63164. -0.3577, -0.5301, -0.4358,
  63165. -0.3169, 0.1063, 0.0158,
  63166. 0.0103, -0.5869, 0.0046,
  63167. -0.0897, -0.4940, 0.3287,
  63168. 0.7119, -0.0154, -0.0918,
  63169. -0.0533, 0.0596, -0.5411,
  63170. 0.0352, -0.0631, 0.5460,
  63171. -0.4776, 0.2847, -0.0271
  63172. ];
  63173. var samplesFactor = 1.0 / numSamples;
  63174. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  63175. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63176. "area", "fallOff", "base", "range", "viewport"
  63177. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63178. this._ssaoPostProcess.onApply = function (effect) {
  63179. if (_this._firstUpdate) {
  63180. effect.setArray3("sampleSphere", sampleSphere);
  63181. effect.setFloat("samplesFactor", samplesFactor);
  63182. effect.setFloat("randTextureTiles", 4.0);
  63183. }
  63184. effect.setFloat("totalStrength", _this.totalStrength);
  63185. effect.setFloat("radius", _this.radius);
  63186. effect.setFloat("area", _this.area);
  63187. effect.setFloat("fallOff", _this.fallOff);
  63188. effect.setFloat("base", _this.base);
  63189. effect.setTexture("textureSampler", _this._depthTexture);
  63190. effect.setTexture("randomSampler", _this._randomTexture);
  63191. };
  63192. };
  63193. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63194. var _this = this;
  63195. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63196. this._ssaoCombinePostProcess.onApply = function (effect) {
  63197. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63198. };
  63199. };
  63200. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  63201. var size = 512;
  63202. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63203. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63204. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63205. var context = this._randomTexture.getContext();
  63206. var rand = function (min, max) {
  63207. return Math.random() * (max - min) + min;
  63208. };
  63209. var randVector = BABYLON.Vector3.Zero();
  63210. for (var x = 0; x < size; x++) {
  63211. for (var y = 0; y < size; y++) {
  63212. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  63213. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  63214. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  63215. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63216. context.fillRect(x, y, 1, 1);
  63217. }
  63218. }
  63219. this._randomTexture.update(false);
  63220. };
  63221. __decorate([
  63222. BABYLON.serialize()
  63223. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  63224. __decorate([
  63225. BABYLON.serialize()
  63226. ], SSAORenderingPipeline.prototype, "radius", void 0);
  63227. __decorate([
  63228. BABYLON.serialize()
  63229. ], SSAORenderingPipeline.prototype, "area", void 0);
  63230. __decorate([
  63231. BABYLON.serialize()
  63232. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  63233. __decorate([
  63234. BABYLON.serialize()
  63235. ], SSAORenderingPipeline.prototype, "base", void 0);
  63236. return SSAORenderingPipeline;
  63237. }(BABYLON.PostProcessRenderPipeline));
  63238. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  63239. })(BABYLON || (BABYLON = {}));
  63240. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  63241. var BABYLON;
  63242. (function (BABYLON) {
  63243. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  63244. __extends(SSAO2RenderingPipeline, _super);
  63245. /**
  63246. * @constructor
  63247. * @param {string} name - The rendering pipeline name
  63248. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63249. * @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 }
  63250. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63251. */
  63252. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  63253. var _this = _super.call(this, scene.getEngine(), name) || this;
  63254. // Members
  63255. /**
  63256. * The PassPostProcess id in the pipeline that contains the original scene color
  63257. * @type {string}
  63258. */
  63259. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63260. /**
  63261. * The SSAO PostProcess id in the pipeline
  63262. * @type {string}
  63263. */
  63264. _this.SSAORenderEffect = "SSAORenderEffect";
  63265. /**
  63266. * The horizontal blur PostProcess id in the pipeline
  63267. * @type {string}
  63268. */
  63269. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63270. /**
  63271. * The vertical blur PostProcess id in the pipeline
  63272. * @type {string}
  63273. */
  63274. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63275. /**
  63276. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63277. * @type {string}
  63278. */
  63279. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63280. /**
  63281. * The output strength of the SSAO post-process. Default value is 1.0.
  63282. * @type {number}
  63283. */
  63284. _this.totalStrength = 1.0;
  63285. /**
  63286. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  63287. * @type {number}
  63288. */
  63289. _this.maxZ = 100.0;
  63290. /**
  63291. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  63292. * @type {number}
  63293. */
  63294. _this.minZAspect = 0.2;
  63295. /**
  63296. * Number of samples used for the SSAO calculations. Default value is 8
  63297. * @type {number}
  63298. */
  63299. _this._samples = 8;
  63300. /**
  63301. * Are we using bilateral blur ?
  63302. * @type {boolean}
  63303. */
  63304. _this._expensiveBlur = true;
  63305. /**
  63306. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  63307. * @type {number}
  63308. */
  63309. _this.radius = 2.0;
  63310. /**
  63311. * The base color of the SSAO post-process
  63312. * The final result is "base + ssao" between [0, 1]
  63313. * @type {number}
  63314. */
  63315. _this.base = 0.1;
  63316. _this._firstUpdate = true;
  63317. _this._scene = scene;
  63318. if (!_this.isSupported) {
  63319. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  63320. return _this;
  63321. }
  63322. var ssaoRatio = ratio.ssaoRatio || ratio;
  63323. var blurRatio = ratio.blurRatio || ratio;
  63324. // Set up assets
  63325. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  63326. _this._createRandomTexture();
  63327. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  63328. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  63329. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63330. _this._createSSAOPostProcess(1.0);
  63331. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  63332. _this._createSSAOCombinePostProcess(blurRatio);
  63333. // Set up pipeline
  63334. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63335. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63336. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63337. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63338. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63339. // Finish
  63340. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63341. if (cameras)
  63342. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63343. return _this;
  63344. }
  63345. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  63346. get: function () {
  63347. return this._samples;
  63348. },
  63349. set: function (n) {
  63350. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  63351. this._samples = n;
  63352. this._sampleSphere = this._generateHemisphere();
  63353. this._firstUpdate = true;
  63354. },
  63355. enumerable: true,
  63356. configurable: true
  63357. });
  63358. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  63359. get: function () {
  63360. return this._expensiveBlur;
  63361. },
  63362. set: function (b) {
  63363. 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"]);
  63364. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  63365. this._expensiveBlur = b;
  63366. this._firstUpdate = true;
  63367. },
  63368. enumerable: true,
  63369. configurable: true
  63370. });
  63371. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  63372. /**
  63373. * Support test.
  63374. * @type {boolean}
  63375. */
  63376. get: function () {
  63377. var engine = BABYLON.Engine.LastCreatedEngine;
  63378. if (!engine) {
  63379. return false;
  63380. }
  63381. return engine.getCaps().drawBuffersExtension;
  63382. },
  63383. enumerable: true,
  63384. configurable: true
  63385. });
  63386. // Public Methods
  63387. /**
  63388. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63389. */
  63390. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63391. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63392. for (var i = 0; i < this._scene.cameras.length; i++) {
  63393. var camera = this._scene.cameras[i];
  63394. this._originalColorPostProcess.dispose(camera);
  63395. this._ssaoPostProcess.dispose(camera);
  63396. this._blurHPostProcess.dispose(camera);
  63397. this._blurVPostProcess.dispose(camera);
  63398. this._ssaoCombinePostProcess.dispose(camera);
  63399. }
  63400. this._randomTexture.dispose();
  63401. if (disableGeometryBufferRenderer)
  63402. this._scene.disableGeometryBufferRenderer();
  63403. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63404. _super.prototype.dispose.call(this);
  63405. };
  63406. // Private Methods
  63407. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63408. var _this = this;
  63409. this._samplerOffsets = [];
  63410. var expensive = this.expensiveBlur;
  63411. for (var i = -8; i < 8; i++) {
  63412. this._samplerOffsets.push(i * 2 + 0.5);
  63413. }
  63414. 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");
  63415. this._blurHPostProcess.onApply = function (effect) {
  63416. if (!_this._scene.activeCamera) {
  63417. return;
  63418. }
  63419. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63420. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63421. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63422. effect.setFloat("radius", _this.radius);
  63423. effect.setTexture("depthSampler", _this._depthTexture);
  63424. if (_this._firstUpdate) {
  63425. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63426. }
  63427. };
  63428. 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");
  63429. this._blurVPostProcess.onApply = function (effect) {
  63430. if (!_this._scene.activeCamera) {
  63431. return;
  63432. }
  63433. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63434. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63435. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63436. effect.setFloat("radius", _this.radius);
  63437. effect.setTexture("depthSampler", _this._depthTexture);
  63438. if (_this._firstUpdate) {
  63439. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63440. _this._firstUpdate = false;
  63441. }
  63442. };
  63443. };
  63444. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63445. this._firstUpdate = true;
  63446. _super.prototype._rebuild.call(this);
  63447. };
  63448. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63449. var numSamples = this.samples;
  63450. var result = [];
  63451. var vector, scale;
  63452. var rand = function (min, max) {
  63453. return Math.random() * (max - min) + min;
  63454. };
  63455. var i = 0;
  63456. while (i < numSamples) {
  63457. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63458. vector.normalize();
  63459. scale = i / numSamples;
  63460. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63461. vector.scaleInPlace(scale);
  63462. result.push(vector.x, vector.y, vector.z);
  63463. i++;
  63464. }
  63465. return result;
  63466. };
  63467. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63468. var _this = this;
  63469. var numSamples = this.samples;
  63470. this._sampleSphere = this._generateHemisphere();
  63471. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63472. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63473. "base", "range", "projection", "near", "far", "texelSize",
  63474. "xViewport", "yViewport", "maxZ", "minZAspect"
  63475. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63476. this._ssaoPostProcess.onApply = function (effect) {
  63477. if (_this._firstUpdate) {
  63478. effect.setArray3("sampleSphere", _this._sampleSphere);
  63479. effect.setFloat("randTextureTiles", 4.0);
  63480. }
  63481. if (!_this._scene.activeCamera) {
  63482. return;
  63483. }
  63484. effect.setFloat("samplesFactor", 1 / _this.samples);
  63485. effect.setFloat("totalStrength", _this.totalStrength);
  63486. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63487. effect.setFloat("radius", _this.radius);
  63488. effect.setFloat("maxZ", _this.maxZ);
  63489. effect.setFloat("minZAspect", _this.minZAspect);
  63490. effect.setFloat("base", _this.base);
  63491. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63492. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63493. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63494. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63495. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63496. effect.setTexture("textureSampler", _this._depthTexture);
  63497. effect.setTexture("normalSampler", _this._normalTexture);
  63498. effect.setTexture("randomSampler", _this._randomTexture);
  63499. };
  63500. };
  63501. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63502. var _this = this;
  63503. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63504. this._ssaoCombinePostProcess.onApply = function (effect) {
  63505. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63506. };
  63507. };
  63508. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63509. var size = 512;
  63510. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63511. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63512. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63513. var context = this._randomTexture.getContext();
  63514. var rand = function (min, max) {
  63515. return Math.random() * (max - min) + min;
  63516. };
  63517. var randVector = BABYLON.Vector3.Zero();
  63518. for (var x = 0; x < size; x++) {
  63519. for (var y = 0; y < size; y++) {
  63520. randVector.x = rand(0.0, 1.0);
  63521. randVector.y = rand(0.0, 1.0);
  63522. randVector.z = 0.0;
  63523. randVector.normalize();
  63524. randVector.scaleInPlace(255);
  63525. randVector.x = Math.floor(randVector.x);
  63526. randVector.y = Math.floor(randVector.y);
  63527. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63528. context.fillRect(x, y, 1, 1);
  63529. }
  63530. }
  63531. this._randomTexture.update(false);
  63532. };
  63533. __decorate([
  63534. BABYLON.serialize()
  63535. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63536. __decorate([
  63537. BABYLON.serialize()
  63538. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63539. __decorate([
  63540. BABYLON.serialize()
  63541. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63542. __decorate([
  63543. BABYLON.serialize("samples")
  63544. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63545. __decorate([
  63546. BABYLON.serialize("expensiveBlur")
  63547. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63548. __decorate([
  63549. BABYLON.serialize()
  63550. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63551. __decorate([
  63552. BABYLON.serialize()
  63553. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63554. return SSAO2RenderingPipeline;
  63555. }(BABYLON.PostProcessRenderPipeline));
  63556. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63557. })(BABYLON || (BABYLON = {}));
  63558. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63559. // BABYLON.JS Chromatic Aberration GLSL Shader
  63560. // Author: Olivier Guyot
  63561. // Separates very slightly R, G and B colors on the edges of the screen
  63562. // Inspired by Francois Tarlier & Martins Upitis
  63563. var BABYLON;
  63564. (function (BABYLON) {
  63565. var LensRenderingPipeline = /** @class */ (function (_super) {
  63566. __extends(LensRenderingPipeline, _super);
  63567. /**
  63568. * @constructor
  63569. *
  63570. * Effect parameters are as follow:
  63571. * {
  63572. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63573. * edge_blur: number; // from 0 to x (1 for realism)
  63574. * distortion: number; // from 0 to x (1 for realism)
  63575. * grain_amount: number; // from 0 to 1
  63576. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63577. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63578. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63579. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63580. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63581. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63582. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63583. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63584. * }
  63585. * Note: if an effect parameter is unset, effect is disabled
  63586. *
  63587. * @param {string} name - The rendering pipeline name
  63588. * @param {object} parameters - An object containing all parameters (see above)
  63589. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63590. * @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)
  63591. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63592. */
  63593. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63594. if (ratio === void 0) { ratio = 1.0; }
  63595. var _this = _super.call(this, scene.getEngine(), name) || this;
  63596. // Lens effects can be of the following:
  63597. // - chromatic aberration (slight shift of RGB colors)
  63598. // - blur on the edge of the lens
  63599. // - lens distortion
  63600. // - depth-of-field blur & highlights enhancing
  63601. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63602. // - grain effect (noise or custom texture)
  63603. // Two additional texture samplers are needed:
  63604. // - depth map (for depth-of-field)
  63605. // - grain texture
  63606. /**
  63607. * The chromatic aberration PostProcess id in the pipeline
  63608. * @type {string}
  63609. */
  63610. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63611. /**
  63612. * The highlights enhancing PostProcess id in the pipeline
  63613. * @type {string}
  63614. */
  63615. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63616. /**
  63617. * The depth-of-field PostProcess id in the pipeline
  63618. * @type {string}
  63619. */
  63620. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63621. _this._scene = scene;
  63622. // Fetch texture samplers
  63623. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63624. if (parameters.grain_texture) {
  63625. _this._grainTexture = parameters.grain_texture;
  63626. }
  63627. else {
  63628. _this._createGrainTexture();
  63629. }
  63630. // save parameters
  63631. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63632. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63633. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63634. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63635. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63636. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63637. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63638. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63639. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63640. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63641. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63642. // Create effects
  63643. _this._createChromaticAberrationPostProcess(ratio);
  63644. _this._createHighlightsPostProcess(ratio);
  63645. _this._createDepthOfFieldPostProcess(ratio / 4);
  63646. // Set up pipeline
  63647. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63648. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63649. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63650. if (_this._highlightsGain === -1) {
  63651. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63652. }
  63653. // Finish
  63654. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63655. if (cameras) {
  63656. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63657. }
  63658. return _this;
  63659. }
  63660. // public methods (self explanatory)
  63661. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63662. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63663. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63664. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63665. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63666. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63667. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63668. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63669. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63670. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63671. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63672. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63673. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63674. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63675. };
  63676. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63677. this._highlightsPostProcess.updateEffect();
  63678. };
  63679. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63680. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63681. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63682. this._highlightsGain = amount;
  63683. };
  63684. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63685. if (this._highlightsGain === -1) {
  63686. this._highlightsGain = 1.0;
  63687. }
  63688. this._highlightsThreshold = amount;
  63689. };
  63690. LensRenderingPipeline.prototype.disableHighlights = function () {
  63691. this._highlightsGain = -1;
  63692. };
  63693. /**
  63694. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63695. */
  63696. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63697. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63698. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63699. this._chromaticAberrationPostProcess = null;
  63700. this._highlightsPostProcess = null;
  63701. this._depthOfFieldPostProcess = null;
  63702. this._grainTexture.dispose();
  63703. if (disableDepthRender)
  63704. this._scene.disableDepthRenderer();
  63705. };
  63706. // colors shifting and distortion
  63707. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63708. var _this = this;
  63709. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63710. [], // samplers
  63711. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63712. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63713. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63714. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63715. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63716. };
  63717. };
  63718. // highlights enhancing
  63719. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63720. var _this = this;
  63721. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63722. [], // samplers
  63723. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63724. this._highlightsPostProcess.onApply = function (effect) {
  63725. effect.setFloat('gain', _this._highlightsGain);
  63726. effect.setFloat('threshold', _this._highlightsThreshold);
  63727. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63728. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63729. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63730. };
  63731. };
  63732. // colors shifting and distortion
  63733. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63734. var _this = this;
  63735. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63736. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63737. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63738. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63739. this._depthOfFieldPostProcess.onApply = function (effect) {
  63740. effect.setTexture("depthSampler", _this._depthTexture);
  63741. effect.setTexture("grainSampler", _this._grainTexture);
  63742. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63743. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63744. effect.setFloat('grain_amount', _this._grainAmount);
  63745. effect.setBool('blur_noise', _this._blurNoise);
  63746. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63747. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63748. effect.setFloat('distortion', _this._distortion);
  63749. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63750. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63751. effect.setFloat('aperture', _this._dofAperture);
  63752. effect.setFloat('darken', _this._dofDarken);
  63753. effect.setFloat('edge_blur', _this._edgeBlur);
  63754. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63755. if (_this._scene.activeCamera) {
  63756. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63757. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63758. }
  63759. };
  63760. };
  63761. // creates a black and white random noise texture, 512x512
  63762. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63763. var size = 512;
  63764. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63765. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63766. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63767. var context = this._grainTexture.getContext();
  63768. var rand = function (min, max) {
  63769. return Math.random() * (max - min) + min;
  63770. };
  63771. var value;
  63772. for (var x = 0; x < size; x++) {
  63773. for (var y = 0; y < size; y++) {
  63774. value = Math.floor(rand(0.42, 0.58) * 255);
  63775. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63776. context.fillRect(x, y, 1, 1);
  63777. }
  63778. }
  63779. this._grainTexture.update(false);
  63780. };
  63781. return LensRenderingPipeline;
  63782. }(BABYLON.PostProcessRenderPipeline));
  63783. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63784. })(BABYLON || (BABYLON = {}));
  63785. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63786. var BABYLON;
  63787. (function (BABYLON) {
  63788. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63789. __extends(StandardRenderingPipeline, _super);
  63790. /**
  63791. * @constructor
  63792. * @param {string} name - The rendering pipeline name
  63793. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63794. * @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)
  63795. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63796. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63797. */
  63798. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63799. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63800. var _this = _super.call(this, scene.getEngine(), name) || this;
  63801. _this.downSampleX4PostProcess = null;
  63802. _this.brightPassPostProcess = null;
  63803. _this.blurHPostProcesses = [];
  63804. _this.blurVPostProcesses = [];
  63805. _this.textureAdderPostProcess = null;
  63806. _this.volumetricLightPostProcess = null;
  63807. _this.volumetricLightSmoothXPostProcess = null;
  63808. _this.volumetricLightSmoothYPostProcess = null;
  63809. _this.volumetricLightMergePostProces = null;
  63810. _this.volumetricLightFinalPostProcess = null;
  63811. _this.luminancePostProcess = null;
  63812. _this.luminanceDownSamplePostProcesses = [];
  63813. _this.hdrPostProcess = null;
  63814. _this.textureAdderFinalPostProcess = null;
  63815. _this.lensFlareFinalPostProcess = null;
  63816. _this.hdrFinalPostProcess = null;
  63817. _this.lensFlarePostProcess = null;
  63818. _this.lensFlareComposePostProcess = null;
  63819. _this.motionBlurPostProcess = null;
  63820. _this.depthOfFieldPostProcess = null;
  63821. // Values
  63822. _this.brightThreshold = 1.0;
  63823. _this.blurWidth = 512.0;
  63824. _this.horizontalBlur = false;
  63825. _this.exposure = 1.0;
  63826. _this.lensTexture = null;
  63827. _this.volumetricLightCoefficient = 0.2;
  63828. _this.volumetricLightPower = 4.0;
  63829. _this.volumetricLightBlurScale = 64.0;
  63830. _this.sourceLight = null;
  63831. _this.hdrMinimumLuminance = 1.0;
  63832. _this.hdrDecreaseRate = 0.5;
  63833. _this.hdrIncreaseRate = 0.5;
  63834. _this.lensColorTexture = null;
  63835. _this.lensFlareStrength = 20.0;
  63836. _this.lensFlareGhostDispersal = 1.4;
  63837. _this.lensFlareHaloWidth = 0.7;
  63838. _this.lensFlareDistortionStrength = 16.0;
  63839. _this.lensStarTexture = null;
  63840. _this.lensFlareDirtTexture = null;
  63841. _this.depthOfFieldDistance = 10.0;
  63842. _this.depthOfFieldBlurWidth = 64.0;
  63843. _this.motionStrength = 1.0;
  63844. // IAnimatable
  63845. _this.animations = [];
  63846. _this._currentDepthOfFieldSource = null;
  63847. _this._hdrCurrentLuminance = 1.0;
  63848. // Getters and setters
  63849. _this._bloomEnabled = true;
  63850. _this._depthOfFieldEnabled = false;
  63851. _this._vlsEnabled = false;
  63852. _this._lensFlareEnabled = false;
  63853. _this._hdrEnabled = false;
  63854. _this._motionBlurEnabled = false;
  63855. _this._motionBlurSamples = 64.0;
  63856. _this._volumetricLightStepsCount = 50.0;
  63857. _this._cameras = cameras || [];
  63858. // Initialize
  63859. _this._scene = scene;
  63860. _this._basePostProcess = originalPostProcess;
  63861. _this._ratio = ratio;
  63862. // Misc
  63863. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63864. // Finish
  63865. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63866. _this._buildPipeline();
  63867. return _this;
  63868. }
  63869. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63870. get: function () {
  63871. return this._bloomEnabled;
  63872. },
  63873. set: function (enabled) {
  63874. if (this._bloomEnabled === enabled) {
  63875. return;
  63876. }
  63877. this._bloomEnabled = enabled;
  63878. this._buildPipeline();
  63879. },
  63880. enumerable: true,
  63881. configurable: true
  63882. });
  63883. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63884. get: function () {
  63885. return this._depthOfFieldEnabled;
  63886. },
  63887. set: function (enabled) {
  63888. if (this._depthOfFieldEnabled === enabled) {
  63889. return;
  63890. }
  63891. this._depthOfFieldEnabled = enabled;
  63892. this._buildPipeline();
  63893. },
  63894. enumerable: true,
  63895. configurable: true
  63896. });
  63897. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63898. get: function () {
  63899. return this._lensFlareEnabled;
  63900. },
  63901. set: function (enabled) {
  63902. if (this._lensFlareEnabled === enabled) {
  63903. return;
  63904. }
  63905. this._lensFlareEnabled = enabled;
  63906. this._buildPipeline();
  63907. },
  63908. enumerable: true,
  63909. configurable: true
  63910. });
  63911. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63912. get: function () {
  63913. return this._hdrEnabled;
  63914. },
  63915. set: function (enabled) {
  63916. if (this._hdrEnabled === enabled) {
  63917. return;
  63918. }
  63919. this._hdrEnabled = enabled;
  63920. this._buildPipeline();
  63921. },
  63922. enumerable: true,
  63923. configurable: true
  63924. });
  63925. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63926. get: function () {
  63927. return this._vlsEnabled;
  63928. },
  63929. set: function (enabled) {
  63930. if (this._vlsEnabled === enabled) {
  63931. return;
  63932. }
  63933. if (enabled) {
  63934. var geometry = this._scene.enableGeometryBufferRenderer();
  63935. if (!geometry) {
  63936. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63937. return;
  63938. }
  63939. }
  63940. this._vlsEnabled = enabled;
  63941. this._buildPipeline();
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63947. get: function () {
  63948. return this._motionBlurEnabled;
  63949. },
  63950. set: function (enabled) {
  63951. if (this._motionBlurEnabled === enabled) {
  63952. return;
  63953. }
  63954. this._motionBlurEnabled = enabled;
  63955. this._buildPipeline();
  63956. },
  63957. enumerable: true,
  63958. configurable: true
  63959. });
  63960. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63961. get: function () {
  63962. return this._volumetricLightStepsCount;
  63963. },
  63964. set: function (count) {
  63965. if (this.volumetricLightPostProcess) {
  63966. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63967. }
  63968. this._volumetricLightStepsCount = count;
  63969. },
  63970. enumerable: true,
  63971. configurable: true
  63972. });
  63973. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63974. get: function () {
  63975. return this._motionBlurSamples;
  63976. },
  63977. set: function (samples) {
  63978. if (this.motionBlurPostProcess) {
  63979. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63980. }
  63981. this._motionBlurSamples = samples;
  63982. },
  63983. enumerable: true,
  63984. configurable: true
  63985. });
  63986. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63987. var _this = this;
  63988. var ratio = this._ratio;
  63989. var scene = this._scene;
  63990. this._disposePostProcesses();
  63991. this._reset();
  63992. // Create pass post-process
  63993. if (!this._basePostProcess) {
  63994. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63995. this.originalPostProcess.onApply = function (effect) {
  63996. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63997. };
  63998. }
  63999. else {
  64000. this.originalPostProcess = this._basePostProcess;
  64001. }
  64002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  64003. this._currentDepthOfFieldSource = this.originalPostProcess;
  64004. if (this._vlsEnabled) {
  64005. // Create volumetric light
  64006. this._createVolumetricLightPostProcess(scene, ratio);
  64007. // Create volumetric light final post-process
  64008. 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);
  64009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  64010. }
  64011. if (this._bloomEnabled) {
  64012. // Create down sample X4 post-process
  64013. this._createDownSampleX4PostProcess(scene, ratio / 2);
  64014. // Create bright pass post-process
  64015. this._createBrightPassPostProcess(scene, ratio / 2);
  64016. // Create gaussian blur post-processes (down sampling blurs)
  64017. this._createBlurPostProcesses(scene, ratio / 4, 1);
  64018. // Create texture adder post-process
  64019. this._createTextureAdderPostProcess(scene, ratio);
  64020. // Create depth-of-field source post-process
  64021. 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);
  64022. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  64023. }
  64024. if (this._lensFlareEnabled) {
  64025. // Create lens flare post-process
  64026. this._createLensFlarePostProcess(scene, ratio);
  64027. // Create depth-of-field source post-process post lens-flare and disable it now
  64028. 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);
  64029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  64030. }
  64031. if (this._hdrEnabled) {
  64032. // Create luminance
  64033. this._createLuminancePostProcesses(scene, this._floatTextureType);
  64034. // Create HDR
  64035. this._createHdrPostProcess(scene, ratio);
  64036. // Create depth-of-field source post-process post hdr and disable it now
  64037. 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);
  64038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  64039. }
  64040. if (this._depthOfFieldEnabled) {
  64041. // Create gaussian blur used by depth-of-field
  64042. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  64043. // Create depth-of-field post-process
  64044. this._createDepthOfFieldPostProcess(scene, ratio);
  64045. }
  64046. if (this._motionBlurEnabled) {
  64047. // Create motion blur post-process
  64048. this._createMotionBlurPostProcess(scene, ratio);
  64049. }
  64050. if (this._cameras !== null) {
  64051. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64052. }
  64053. };
  64054. // Down Sample X4 Post-Processs
  64055. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  64056. var _this = this;
  64057. var downSampleX4Offsets = new Array(32);
  64058. 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);
  64059. this.downSampleX4PostProcess.onApply = function (effect) {
  64060. var id = 0;
  64061. var width = _this.downSampleX4PostProcess.width;
  64062. var height = _this.downSampleX4PostProcess.height;
  64063. for (var i = -2; i < 2; i++) {
  64064. for (var j = -2; j < 2; j++) {
  64065. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  64066. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  64067. id += 2;
  64068. }
  64069. }
  64070. effect.setArray2("dsOffsets", downSampleX4Offsets);
  64071. };
  64072. // Add to pipeline
  64073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  64074. };
  64075. // Brightpass Post-Process
  64076. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  64077. var _this = this;
  64078. var brightOffsets = new Array(8);
  64079. 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);
  64080. this.brightPassPostProcess.onApply = function (effect) {
  64081. var sU = (1.0 / _this.brightPassPostProcess.width);
  64082. var sV = (1.0 / _this.brightPassPostProcess.height);
  64083. brightOffsets[0] = -0.5 * sU;
  64084. brightOffsets[1] = 0.5 * sV;
  64085. brightOffsets[2] = 0.5 * sU;
  64086. brightOffsets[3] = 0.5 * sV;
  64087. brightOffsets[4] = -0.5 * sU;
  64088. brightOffsets[5] = -0.5 * sV;
  64089. brightOffsets[6] = 0.5 * sU;
  64090. brightOffsets[7] = -0.5 * sV;
  64091. effect.setArray2("dsOffsets", brightOffsets);
  64092. effect.setFloat("brightThreshold", _this.brightThreshold);
  64093. };
  64094. // Add to pipeline
  64095. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  64096. };
  64097. // Create blur H&V post-processes
  64098. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  64099. var _this = this;
  64100. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  64101. var engine = scene.getEngine();
  64102. 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);
  64103. 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);
  64104. blurX.onActivateObservable.add(function () {
  64105. var dw = blurX.width / engine.getRenderWidth();
  64106. blurX.kernel = _this[blurWidthKey] * dw;
  64107. });
  64108. blurY.onActivateObservable.add(function () {
  64109. var dw = blurY.height / engine.getRenderHeight();
  64110. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  64111. });
  64112. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  64113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  64114. this.blurHPostProcesses.push(blurX);
  64115. this.blurVPostProcesses.push(blurY);
  64116. };
  64117. // Create texture adder post-process
  64118. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  64119. var _this = this;
  64120. 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);
  64121. this.textureAdderPostProcess.onApply = function (effect) {
  64122. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  64123. effect.setTexture("lensSampler", _this.lensTexture);
  64124. effect.setFloat("exposure", _this.exposure);
  64125. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  64126. };
  64127. // Add to pipeline
  64128. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  64129. };
  64130. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  64131. var _this = this;
  64132. var geometryRenderer = scene.enableGeometryBufferRenderer();
  64133. geometryRenderer.enablePosition = true;
  64134. var geometry = geometryRenderer.getGBuffer();
  64135. // Base post-process
  64136. 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));
  64137. var depthValues = BABYLON.Vector2.Zero();
  64138. this.volumetricLightPostProcess.onApply = function (effect) {
  64139. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  64140. var generator = _this.sourceLight.getShadowGenerator();
  64141. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  64142. effect.setTexture("positionSampler", geometry.textures[2]);
  64143. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  64144. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  64145. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  64146. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  64147. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  64148. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  64149. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  64150. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  64151. effect.setVector2("depthValues", depthValues);
  64152. }
  64153. };
  64154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  64155. // Smooth
  64156. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  64157. // Merge
  64158. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  64159. this.volumetricLightMergePostProces.onApply = function (effect) {
  64160. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  64161. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  64162. };
  64163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  64164. };
  64165. // Create luminance
  64166. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  64167. var _this = this;
  64168. // Create luminance
  64169. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  64170. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  64171. var offsets = [];
  64172. this.luminancePostProcess.onApply = function (effect) {
  64173. var sU = (1.0 / _this.luminancePostProcess.width);
  64174. var sV = (1.0 / _this.luminancePostProcess.height);
  64175. offsets[0] = -0.5 * sU;
  64176. offsets[1] = 0.5 * sV;
  64177. offsets[2] = 0.5 * sU;
  64178. offsets[3] = 0.5 * sV;
  64179. offsets[4] = -0.5 * sU;
  64180. offsets[5] = -0.5 * sV;
  64181. offsets[6] = 0.5 * sU;
  64182. offsets[7] = -0.5 * sV;
  64183. effect.setArray2("lumOffsets", offsets);
  64184. };
  64185. // Add to pipeline
  64186. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  64187. // Create down sample luminance
  64188. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  64189. var size = Math.pow(3, i);
  64190. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  64191. if (i === 0) {
  64192. defines += "#define FINAL_DOWN_SAMPLER";
  64193. }
  64194. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  64195. this.luminanceDownSamplePostProcesses.push(postProcess);
  64196. }
  64197. // Create callbacks and add effects
  64198. var lastLuminance = this.luminancePostProcess;
  64199. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  64200. var downSampleOffsets = new Array(18);
  64201. pp.onApply = function (effect) {
  64202. if (!lastLuminance) {
  64203. return;
  64204. }
  64205. var id = 0;
  64206. for (var x = -1; x < 2; x++) {
  64207. for (var y = -1; y < 2; y++) {
  64208. downSampleOffsets[id] = x / lastLuminance.width;
  64209. downSampleOffsets[id + 1] = y / lastLuminance.height;
  64210. id += 2;
  64211. }
  64212. }
  64213. effect.setArray2("dsOffsets", downSampleOffsets);
  64214. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  64215. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64216. lastLuminance = _this.luminancePostProcess;
  64217. }
  64218. else {
  64219. lastLuminance = pp;
  64220. }
  64221. };
  64222. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64223. pp.onAfterRender = function (effect) {
  64224. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  64225. 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);
  64226. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  64227. };
  64228. }
  64229. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  64230. });
  64231. };
  64232. // Create HDR post-process
  64233. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  64234. var _this = this;
  64235. 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);
  64236. var outputLiminance = 1;
  64237. var time = 0;
  64238. var lastTime = 0;
  64239. this.hdrPostProcess.onApply = function (effect) {
  64240. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  64241. time += scene.getEngine().getDeltaTime();
  64242. if (outputLiminance < 0) {
  64243. outputLiminance = _this._hdrCurrentLuminance;
  64244. }
  64245. else {
  64246. var dt = (lastTime - time) / 1000.0;
  64247. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  64248. outputLiminance += _this.hdrDecreaseRate * dt;
  64249. }
  64250. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  64251. outputLiminance -= _this.hdrIncreaseRate * dt;
  64252. }
  64253. else {
  64254. outputLiminance = _this._hdrCurrentLuminance;
  64255. }
  64256. }
  64257. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  64258. effect.setFloat("averageLuminance", outputLiminance);
  64259. lastTime = time;
  64260. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  64261. };
  64262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  64263. };
  64264. // Create lens flare post-process
  64265. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  64266. var _this = this;
  64267. 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);
  64268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  64269. this._createBlurPostProcesses(scene, ratio / 4, 2);
  64270. 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);
  64271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  64272. var resolution = new BABYLON.Vector2(0, 0);
  64273. // Lens flare
  64274. this.lensFlarePostProcess.onApply = function (effect) {
  64275. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  64276. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  64277. effect.setFloat("strength", _this.lensFlareStrength);
  64278. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  64279. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  64280. // Shift
  64281. resolution.x = _this.lensFlarePostProcess.width;
  64282. resolution.y = _this.lensFlarePostProcess.height;
  64283. effect.setVector2("resolution", resolution);
  64284. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  64285. };
  64286. // Compose
  64287. 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);
  64288. 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);
  64289. this.lensFlareComposePostProcess.onApply = function (effect) {
  64290. if (!_this._scene.activeCamera) {
  64291. return;
  64292. }
  64293. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64294. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  64295. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  64296. // Lens start rotation matrix
  64297. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  64298. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  64299. 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));
  64300. camRot *= 4.0;
  64301. 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);
  64302. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  64303. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  64304. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  64305. };
  64306. };
  64307. // Create depth-of-field post-process
  64308. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  64309. var _this = this;
  64310. 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);
  64311. this.depthOfFieldPostProcess.onApply = function (effect) {
  64312. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64313. effect.setTexture("depthSampler", _this._getDepthTexture());
  64314. effect.setFloat("distance", _this.depthOfFieldDistance);
  64315. };
  64316. // Add to pipeline
  64317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  64318. };
  64319. // Create motion blur post-process
  64320. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  64321. var _this = this;
  64322. 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);
  64323. var motionScale = 0;
  64324. var prevViewProjection = BABYLON.Matrix.Identity();
  64325. var invViewProjection = BABYLON.Matrix.Identity();
  64326. var viewProjection = BABYLON.Matrix.Identity();
  64327. var screenSize = BABYLON.Vector2.Zero();
  64328. this.motionBlurPostProcess.onApply = function (effect) {
  64329. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  64330. viewProjection.invertToRef(invViewProjection);
  64331. effect.setMatrix("inverseViewProjection", invViewProjection);
  64332. effect.setMatrix("prevViewProjection", prevViewProjection);
  64333. prevViewProjection = viewProjection;
  64334. screenSize.x = _this.motionBlurPostProcess.width;
  64335. screenSize.y = _this.motionBlurPostProcess.height;
  64336. effect.setVector2("screenSize", screenSize);
  64337. motionScale = scene.getEngine().getFps() / 60.0;
  64338. effect.setFloat("motionScale", motionScale);
  64339. effect.setFloat("motionStrength", _this.motionStrength);
  64340. effect.setTexture("depthSampler", _this._getDepthTexture());
  64341. };
  64342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  64343. };
  64344. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  64345. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  64346. var renderer = this._scene.enableGeometryBufferRenderer();
  64347. return renderer.getGBuffer().textures[0];
  64348. }
  64349. return this._scene.enableDepthRenderer().getDepthMap();
  64350. };
  64351. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  64352. for (var i = 0; i < this._cameras.length; i++) {
  64353. var camera = this._cameras[i];
  64354. if (this.originalPostProcess) {
  64355. this.originalPostProcess.dispose(camera);
  64356. }
  64357. if (this.downSampleX4PostProcess) {
  64358. this.downSampleX4PostProcess.dispose(camera);
  64359. }
  64360. if (this.brightPassPostProcess) {
  64361. this.brightPassPostProcess.dispose(camera);
  64362. }
  64363. if (this.textureAdderPostProcess) {
  64364. this.textureAdderPostProcess.dispose(camera);
  64365. }
  64366. if (this.textureAdderFinalPostProcess) {
  64367. this.textureAdderFinalPostProcess.dispose(camera);
  64368. }
  64369. if (this.volumetricLightPostProcess) {
  64370. this.volumetricLightPostProcess.dispose(camera);
  64371. }
  64372. if (this.volumetricLightSmoothXPostProcess) {
  64373. this.volumetricLightSmoothXPostProcess.dispose(camera);
  64374. }
  64375. if (this.volumetricLightSmoothYPostProcess) {
  64376. this.volumetricLightSmoothYPostProcess.dispose(camera);
  64377. }
  64378. if (this.volumetricLightMergePostProces) {
  64379. this.volumetricLightMergePostProces.dispose(camera);
  64380. }
  64381. if (this.volumetricLightFinalPostProcess) {
  64382. this.volumetricLightFinalPostProcess.dispose(camera);
  64383. }
  64384. if (this.lensFlarePostProcess) {
  64385. this.lensFlarePostProcess.dispose(camera);
  64386. }
  64387. if (this.lensFlareComposePostProcess) {
  64388. this.lensFlareComposePostProcess.dispose(camera);
  64389. }
  64390. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64391. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64392. }
  64393. if (this.luminancePostProcess) {
  64394. this.luminancePostProcess.dispose(camera);
  64395. }
  64396. if (this.hdrPostProcess) {
  64397. this.hdrPostProcess.dispose(camera);
  64398. }
  64399. if (this.hdrFinalPostProcess) {
  64400. this.hdrFinalPostProcess.dispose(camera);
  64401. }
  64402. if (this.depthOfFieldPostProcess) {
  64403. this.depthOfFieldPostProcess.dispose(camera);
  64404. }
  64405. if (this.motionBlurPostProcess) {
  64406. this.motionBlurPostProcess.dispose(camera);
  64407. }
  64408. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64409. this.blurHPostProcesses[j].dispose(camera);
  64410. }
  64411. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64412. this.blurVPostProcesses[j].dispose(camera);
  64413. }
  64414. }
  64415. this.originalPostProcess = null;
  64416. this.downSampleX4PostProcess = null;
  64417. this.brightPassPostProcess = null;
  64418. this.textureAdderPostProcess = null;
  64419. this.textureAdderFinalPostProcess = null;
  64420. this.volumetricLightPostProcess = null;
  64421. this.volumetricLightSmoothXPostProcess = null;
  64422. this.volumetricLightSmoothYPostProcess = null;
  64423. this.volumetricLightMergePostProces = null;
  64424. this.volumetricLightFinalPostProcess = null;
  64425. this.lensFlarePostProcess = null;
  64426. this.lensFlareComposePostProcess = null;
  64427. this.luminancePostProcess = null;
  64428. this.hdrPostProcess = null;
  64429. this.hdrFinalPostProcess = null;
  64430. this.depthOfFieldPostProcess = null;
  64431. this.motionBlurPostProcess = null;
  64432. this.luminanceDownSamplePostProcesses = [];
  64433. this.blurHPostProcesses = [];
  64434. this.blurVPostProcesses = [];
  64435. };
  64436. // Dispose
  64437. StandardRenderingPipeline.prototype.dispose = function () {
  64438. this._disposePostProcesses();
  64439. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64440. _super.prototype.dispose.call(this);
  64441. };
  64442. // Serialize rendering pipeline
  64443. StandardRenderingPipeline.prototype.serialize = function () {
  64444. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64445. serializationObject.customType = "StandardRenderingPipeline";
  64446. return serializationObject;
  64447. };
  64448. /**
  64449. * Static members
  64450. */
  64451. // Parse serialized pipeline
  64452. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64453. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64454. };
  64455. // Luminance steps
  64456. StandardRenderingPipeline.LuminanceSteps = 6;
  64457. __decorate([
  64458. BABYLON.serialize()
  64459. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64460. __decorate([
  64461. BABYLON.serialize()
  64462. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64463. __decorate([
  64464. BABYLON.serialize()
  64465. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64466. __decorate([
  64467. BABYLON.serialize()
  64468. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64469. __decorate([
  64470. BABYLON.serializeAsTexture("lensTexture")
  64471. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64472. __decorate([
  64473. BABYLON.serialize()
  64474. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64475. __decorate([
  64476. BABYLON.serialize()
  64477. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64478. __decorate([
  64479. BABYLON.serialize()
  64480. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64481. __decorate([
  64482. BABYLON.serialize()
  64483. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64484. __decorate([
  64485. BABYLON.serialize()
  64486. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64487. __decorate([
  64488. BABYLON.serialize()
  64489. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64490. __decorate([
  64491. BABYLON.serializeAsTexture("lensColorTexture")
  64492. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64493. __decorate([
  64494. BABYLON.serialize()
  64495. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64496. __decorate([
  64497. BABYLON.serialize()
  64498. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64499. __decorate([
  64500. BABYLON.serialize()
  64501. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64502. __decorate([
  64503. BABYLON.serialize()
  64504. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64505. __decorate([
  64506. BABYLON.serializeAsTexture("lensStarTexture")
  64507. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64508. __decorate([
  64509. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64510. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64511. __decorate([
  64512. BABYLON.serialize()
  64513. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64514. __decorate([
  64515. BABYLON.serialize()
  64516. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64517. __decorate([
  64518. BABYLON.serialize()
  64519. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64520. __decorate([
  64521. BABYLON.serialize()
  64522. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64523. __decorate([
  64524. BABYLON.serialize()
  64525. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64526. __decorate([
  64527. BABYLON.serialize()
  64528. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64529. __decorate([
  64530. BABYLON.serialize()
  64531. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64532. __decorate([
  64533. BABYLON.serialize()
  64534. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64535. __decorate([
  64536. BABYLON.serialize()
  64537. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64538. __decorate([
  64539. BABYLON.serialize()
  64540. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64541. __decorate([
  64542. BABYLON.serialize()
  64543. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64544. __decorate([
  64545. BABYLON.serialize()
  64546. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64547. return StandardRenderingPipeline;
  64548. }(BABYLON.PostProcessRenderPipeline));
  64549. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64550. })(BABYLON || (BABYLON = {}));
  64551. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64552. var BABYLON;
  64553. (function (BABYLON) {
  64554. var FxaaPostProcess = /** @class */ (function (_super) {
  64555. __extends(FxaaPostProcess, _super);
  64556. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64557. if (camera === void 0) { camera = null; }
  64558. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64559. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64560. _this.onApplyObservable.add(function (effect) {
  64561. var texelSize = _this.texelSize;
  64562. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64563. });
  64564. return _this;
  64565. }
  64566. return FxaaPostProcess;
  64567. }(BABYLON.PostProcess));
  64568. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64569. })(BABYLON || (BABYLON = {}));
  64570. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64571. var BABYLON;
  64572. (function (BABYLON) {
  64573. /**
  64574. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64575. */
  64576. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64577. __extends(CircleOfConfusionPostProcess, _super);
  64578. /**
  64579. * Creates a new instance of @see CircleOfConfusionPostProcess
  64580. * @param name The name of the effect.
  64581. * @param scene The scene the effect belongs to.
  64582. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64583. * @param options The required width/height ratio to downsize to before computing the render pass.
  64584. * @param camera The camera to apply the render pass to.
  64585. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64586. * @param engine The engine which the post process will be applied. (default: current engine)
  64587. * @param reusable If the post process can be reused on the same frame. (default: false)
  64588. * @param textureType Type of textures used when performing the post process. (default: 0)
  64589. */
  64590. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64591. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64592. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64593. /**
  64594. * 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.
  64595. */
  64596. _this.lensSize = 50;
  64597. /**
  64598. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64599. */
  64600. _this.fStop = 1.4;
  64601. /**
  64602. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64603. */
  64604. _this.focusDistance = 2000;
  64605. /**
  64606. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64607. */
  64608. _this.focalLength = 50;
  64609. _this.onApplyObservable.add(function (effect) {
  64610. effect.setTexture("depthSampler", depthTexture);
  64611. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64612. var aperture = _this.lensSize / _this.fStop;
  64613. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64614. effect.setFloat('focusDistance', _this.focusDistance);
  64615. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64616. if (scene.activeCamera) {
  64617. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64618. }
  64619. });
  64620. return _this;
  64621. }
  64622. return CircleOfConfusionPostProcess;
  64623. }(BABYLON.PostProcess));
  64624. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64625. })(BABYLON || (BABYLON = {}));
  64626. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64627. var BABYLON;
  64628. (function (BABYLON) {
  64629. /**
  64630. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64631. */
  64632. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64633. __extends(DepthOfFieldMergePostProcess, _super);
  64634. /**
  64635. * Creates a new instance of @see CircleOfConfusionPostProcess
  64636. * @param name The name of the effect.
  64637. * @param original The non-blurred image to be modified
  64638. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64639. * @param options The required width/height ratio to downsize to before computing the render pass.
  64640. * @param camera The camera to apply the render pass to.
  64641. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64642. * @param engine The engine which the post process will be applied. (default: current engine)
  64643. * @param reusable If the post process can be reused on the same frame. (default: false)
  64644. * @param textureType Type of textures used when performing the post process. (default: 0)
  64645. */
  64646. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64647. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64648. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64649. _this.onApplyObservable.add(function (effect) {
  64650. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64651. effect.setTextureFromPostProcess("originalSampler", original);
  64652. });
  64653. return _this;
  64654. }
  64655. return DepthOfFieldMergePostProcess;
  64656. }(BABYLON.PostProcess));
  64657. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64658. })(BABYLON || (BABYLON = {}));
  64659. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64660. var BABYLON;
  64661. (function (BABYLON) {
  64662. /**
  64663. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64664. */
  64665. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64666. __extends(DepthOfFieldEffect, _super);
  64667. /**
  64668. * Creates a new instance of @see DepthOfFieldEffect
  64669. * @param scene The scene the effect belongs to.
  64670. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64671. */
  64672. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64673. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64674. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY, _this._depthOfFieldBlurX, _this._depthOfFieldMerge]; }, true) || this;
  64675. // Enable and get current depth map
  64676. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64677. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64678. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64679. // Capture circle of confusion texture
  64680. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64681. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64682. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64683. _this._depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this._circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64684. _this._depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64685. // Merge blurred images with original image based on circleOfConfusion
  64686. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64687. return _this;
  64688. }
  64689. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64690. get: function () {
  64691. return this._depthOfFieldBlurX.kernel;
  64692. },
  64693. /**
  64694. * The size of the kernel to be used for the blur
  64695. */
  64696. set: function (value) {
  64697. this._depthOfFieldBlurX.kernel = value;
  64698. this._depthOfFieldBlurY.kernel = value;
  64699. },
  64700. enumerable: true,
  64701. configurable: true
  64702. });
  64703. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64704. get: function () {
  64705. return this._circleOfConfusion.focalLength;
  64706. },
  64707. /**
  64708. * The focal the length of the camera used in the effect
  64709. */
  64710. set: function (value) {
  64711. this._circleOfConfusion.focalLength = value;
  64712. },
  64713. enumerable: true,
  64714. configurable: true
  64715. });
  64716. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64717. get: function () {
  64718. return this._circleOfConfusion.fStop;
  64719. },
  64720. /**
  64721. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64722. */
  64723. set: function (value) {
  64724. this._circleOfConfusion.fStop = value;
  64725. },
  64726. enumerable: true,
  64727. configurable: true
  64728. });
  64729. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64730. get: function () {
  64731. return this._circleOfConfusion.focusDistance;
  64732. },
  64733. /**
  64734. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64735. */
  64736. set: function (value) {
  64737. this._circleOfConfusion.focusDistance = value;
  64738. },
  64739. enumerable: true,
  64740. configurable: true
  64741. });
  64742. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64743. get: function () {
  64744. return this._circleOfConfusion.lensSize;
  64745. },
  64746. /**
  64747. * 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.
  64748. */
  64749. set: function (value) {
  64750. this._circleOfConfusion.lensSize = value;
  64751. },
  64752. enumerable: true,
  64753. configurable: true
  64754. });
  64755. /**
  64756. * Disposes each of the internal effects for a given camera.
  64757. * @param camera The camera to dispose the effect on.
  64758. */
  64759. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64760. this._depthOfFieldPass.dispose(camera);
  64761. this._circleOfConfusion.dispose(camera);
  64762. this._depthOfFieldBlurX.dispose(camera);
  64763. this._depthOfFieldBlurY.dispose(camera);
  64764. this._depthOfFieldMerge.dispose(camera);
  64765. };
  64766. return DepthOfFieldEffect;
  64767. }(BABYLON.PostProcessRenderEffect));
  64768. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64769. })(BABYLON || (BABYLON = {}));
  64770. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64771. var BABYLON;
  64772. (function (BABYLON) {
  64773. /**
  64774. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  64775. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  64776. */
  64777. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64778. __extends(DefaultRenderingPipeline, _super);
  64779. /**
  64780. * @constructor
  64781. * @param {string} name - The rendering pipeline name
  64782. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64783. * @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)
  64784. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64785. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64786. */
  64787. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64788. if (automaticBuild === void 0) { automaticBuild = true; }
  64789. var _this = _super.call(this, scene.getEngine(), name) || this;
  64790. /**
  64791. * ID of the pass post process used for bloom,
  64792. */
  64793. _this.PassPostProcessId = "PassPostProcessEffect";
  64794. /**
  64795. * ID of the highlight post process used for bloom,
  64796. */
  64797. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64798. /**
  64799. * ID of the blurX post process used for bloom,
  64800. */
  64801. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64802. /**
  64803. * ID of the blurY post process used for bloom,
  64804. */
  64805. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64806. /**
  64807. * ID of the copy back post process used for bloom,
  64808. */
  64809. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  64810. /**
  64811. * ID of the image processing post process;
  64812. */
  64813. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  64814. /**
  64815. * ID of the Fast Approximate Anti-Aliasing post process;
  64816. */
  64817. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  64818. /**
  64819. * ID of the final merge post process;
  64820. */
  64821. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  64822. /**
  64823. * Animations which can be used to tweak settings over a period of time
  64824. */
  64825. _this.animations = [];
  64826. // Values
  64827. _this._bloomEnabled = false;
  64828. _this._depthOfFieldEnabled = false;
  64829. _this._fxaaEnabled = false;
  64830. _this._imageProcessingEnabled = true;
  64831. _this._bloomScale = 0.6;
  64832. _this._buildAllowed = true;
  64833. /**
  64834. * Specifies the size of the bloom blur kernel, relative to the final output size
  64835. */
  64836. _this.bloomKernel = 64;
  64837. /**
  64838. * Specifies the weight of the bloom in the final rendering
  64839. */
  64840. _this._bloomWeight = 0.15;
  64841. _this._cameras = cameras || [];
  64842. _this._buildAllowed = automaticBuild;
  64843. // Initialize
  64844. _this._scene = scene;
  64845. var caps = _this._scene.getEngine().getCaps();
  64846. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  64847. // Misc
  64848. if (_this._hdr) {
  64849. if (caps.textureHalfFloatRender) {
  64850. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64851. }
  64852. else if (caps.textureFloatRender) {
  64853. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64854. }
  64855. }
  64856. else {
  64857. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64858. }
  64859. // Attach
  64860. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64861. _this._buildPipeline();
  64862. return _this;
  64863. }
  64864. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  64865. get: function () {
  64866. return this._bloomWeight;
  64867. },
  64868. /**
  64869. * The strength of the bloom.
  64870. */
  64871. set: function (value) {
  64872. if (this._bloomWeight === value) {
  64873. return;
  64874. }
  64875. this._bloomWeight = value;
  64876. if (this._hdr && this.copyBack) {
  64877. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  64878. }
  64879. },
  64880. enumerable: true,
  64881. configurable: true
  64882. });
  64883. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  64884. get: function () {
  64885. return this._bloomScale;
  64886. },
  64887. /**
  64888. * The scale of the bloom, lower value will provide better performance.
  64889. */
  64890. set: function (value) {
  64891. if (this._bloomScale === value) {
  64892. return;
  64893. }
  64894. this._bloomScale = value;
  64895. this._buildPipeline();
  64896. },
  64897. enumerable: true,
  64898. configurable: true
  64899. });
  64900. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  64901. get: function () {
  64902. return this._bloomEnabled;
  64903. },
  64904. /**
  64905. * Enable or disable the bloom from the pipeline
  64906. */
  64907. set: function (enabled) {
  64908. if (this._bloomEnabled === enabled) {
  64909. return;
  64910. }
  64911. this._bloomEnabled = enabled;
  64912. this._buildPipeline();
  64913. },
  64914. enumerable: true,
  64915. configurable: true
  64916. });
  64917. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  64918. /**
  64919. * If the depth of field is enabled.
  64920. */
  64921. get: function () {
  64922. return this._depthOfFieldEnabled;
  64923. },
  64924. set: function (enabled) {
  64925. if (this._depthOfFieldEnabled === enabled) {
  64926. return;
  64927. }
  64928. this._depthOfFieldEnabled = enabled;
  64929. this._buildPipeline();
  64930. },
  64931. enumerable: true,
  64932. configurable: true
  64933. });
  64934. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  64935. get: function () {
  64936. return this._fxaaEnabled;
  64937. },
  64938. /**
  64939. * If the anti aliasing is enabled.
  64940. */
  64941. set: function (enabled) {
  64942. if (this._fxaaEnabled === enabled) {
  64943. return;
  64944. }
  64945. this._fxaaEnabled = enabled;
  64946. this._buildPipeline();
  64947. },
  64948. enumerable: true,
  64949. configurable: true
  64950. });
  64951. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  64952. get: function () {
  64953. return this._imageProcessingEnabled;
  64954. },
  64955. /**
  64956. * If image processing is enabled.
  64957. */
  64958. set: function (enabled) {
  64959. if (this._imageProcessingEnabled === enabled) {
  64960. return;
  64961. }
  64962. this._imageProcessingEnabled = enabled;
  64963. this._buildPipeline();
  64964. },
  64965. enumerable: true,
  64966. configurable: true
  64967. });
  64968. /**
  64969. * Force the compilation of the entire pipeline.
  64970. */
  64971. DefaultRenderingPipeline.prototype.prepare = function () {
  64972. var previousState = this._buildAllowed;
  64973. this._buildAllowed = true;
  64974. this._buildPipeline();
  64975. this._buildAllowed = previousState;
  64976. };
  64977. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  64978. var _this = this;
  64979. if (!this._buildAllowed) {
  64980. return;
  64981. }
  64982. var engine = this._scene.getEngine();
  64983. this._disposePostProcesses();
  64984. this._reset();
  64985. if (this.bloomEnabled) {
  64986. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64987. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  64988. if (!this._hdr) {
  64989. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64990. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  64991. this.highlights.autoClear = false;
  64992. this.highlights.alwaysForcePOT = true;
  64993. }
  64994. 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);
  64995. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  64996. this.blurX.alwaysForcePOT = true;
  64997. this.blurX.autoClear = false;
  64998. this.blurX.onActivateObservable.add(function () {
  64999. var dw = _this.blurX.width / engine.getRenderWidth(true);
  65000. _this.blurX.kernel = _this.bloomKernel * dw;
  65001. });
  65002. 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);
  65003. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  65004. this.blurY.alwaysForcePOT = true;
  65005. this.blurY.autoClear = false;
  65006. this.blurY.onActivateObservable.add(function () {
  65007. var dh = _this.blurY.height / engine.getRenderHeight(true);
  65008. _this.blurY.kernel = _this.bloomKernel * dh;
  65009. });
  65010. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65011. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  65012. this.copyBack.alwaysForcePOT = true;
  65013. if (this._hdr) {
  65014. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  65015. var w = this.bloomWeight;
  65016. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  65017. }
  65018. else {
  65019. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  65020. }
  65021. this.copyBack.autoClear = false;
  65022. }
  65023. if (this.depthOfFieldEnabled) {
  65024. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  65025. this.addEffect(this.depthOfField);
  65026. }
  65027. if (this._imageProcessingEnabled) {
  65028. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65029. if (this._hdr) {
  65030. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  65031. }
  65032. else {
  65033. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  65034. }
  65035. }
  65036. if (this.fxaaEnabled) {
  65037. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65038. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  65039. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  65040. }
  65041. else if (this._hdr && this.imageProcessing) {
  65042. this.finalMerge = this.imageProcessing;
  65043. }
  65044. else {
  65045. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65046. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  65047. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  65048. }
  65049. if (this.bloomEnabled) {
  65050. if (this._hdr) {
  65051. this.copyBack.shareOutputWith(this.blurX);
  65052. if (this.imageProcessing) {
  65053. this.imageProcessing.shareOutputWith(this.pass);
  65054. this.imageProcessing.autoClear = false;
  65055. }
  65056. else if (this.fxaa) {
  65057. this.fxaa.shareOutputWith(this.pass);
  65058. }
  65059. else {
  65060. this.finalMerge.shareOutputWith(this.pass);
  65061. }
  65062. }
  65063. else {
  65064. if (this.fxaa) {
  65065. this.fxaa.shareOutputWith(this.pass);
  65066. }
  65067. else {
  65068. this.finalMerge.shareOutputWith(this.pass);
  65069. }
  65070. }
  65071. }
  65072. if (this._cameras !== null) {
  65073. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65074. }
  65075. };
  65076. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  65077. for (var i = 0; i < this._cameras.length; i++) {
  65078. var camera = this._cameras[i];
  65079. if (this.pass) {
  65080. this.pass.dispose(camera);
  65081. }
  65082. if (this.highlights) {
  65083. this.highlights.dispose(camera);
  65084. }
  65085. if (this.blurX) {
  65086. this.blurX.dispose(camera);
  65087. }
  65088. if (this.blurY) {
  65089. this.blurY.dispose(camera);
  65090. }
  65091. if (this.copyBack) {
  65092. this.copyBack.dispose(camera);
  65093. }
  65094. if (this.imageProcessing) {
  65095. this.imageProcessing.dispose(camera);
  65096. }
  65097. if (this.fxaa) {
  65098. this.fxaa.dispose(camera);
  65099. }
  65100. if (this.finalMerge) {
  65101. this.finalMerge.dispose(camera);
  65102. }
  65103. if (this.depthOfField) {
  65104. this.depthOfField.disposeEffects(camera);
  65105. }
  65106. }
  65107. this.pass = null;
  65108. this.highlights = null;
  65109. this.blurX = null;
  65110. this.blurY = null;
  65111. this.copyBack = null;
  65112. this.imageProcessing = null;
  65113. this.fxaa = null;
  65114. this.finalMerge = null;
  65115. this.depthOfField = null;
  65116. };
  65117. /**
  65118. * Dispose of the pipeline and stop all post processes
  65119. */
  65120. DefaultRenderingPipeline.prototype.dispose = function () {
  65121. this._disposePostProcesses();
  65122. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  65123. _super.prototype.dispose.call(this);
  65124. };
  65125. /**
  65126. * Serialize the rendering pipeline (Used when exporting)
  65127. * @returns the serialized object
  65128. */
  65129. DefaultRenderingPipeline.prototype.serialize = function () {
  65130. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  65131. serializationObject.customType = "DefaultRenderingPipeline";
  65132. return serializationObject;
  65133. };
  65134. /**
  65135. * Parse the serialized pipeline
  65136. * @param source Source pipeline.
  65137. * @param scene The scene to load the pipeline to.
  65138. * @param rootUrl The URL of the serialized pipeline.
  65139. * @returns An instantiated pipeline from the serialized object.
  65140. */
  65141. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  65142. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  65143. };
  65144. __decorate([
  65145. BABYLON.serialize()
  65146. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  65147. __decorate([
  65148. BABYLON.serialize()
  65149. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  65150. __decorate([
  65151. BABYLON.serialize()
  65152. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  65153. __decorate([
  65154. BABYLON.serialize()
  65155. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  65156. __decorate([
  65157. BABYLON.serialize()
  65158. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  65159. __decorate([
  65160. BABYLON.serialize()
  65161. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  65162. __decorate([
  65163. BABYLON.serialize()
  65164. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  65165. __decorate([
  65166. BABYLON.serialize()
  65167. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  65168. __decorate([
  65169. BABYLON.serialize()
  65170. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  65171. return DefaultRenderingPipeline;
  65172. }(BABYLON.PostProcessRenderPipeline));
  65173. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  65174. })(BABYLON || (BABYLON = {}));
  65175. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  65176. var BABYLON;
  65177. (function (BABYLON) {
  65178. /**
  65179. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  65180. */
  65181. var GeometryBufferRenderer = /** @class */ (function () {
  65182. /**
  65183. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  65184. * @param scene The scene the buffer belongs to
  65185. * @param ratio How big is the buffer related to the main canvas.
  65186. */
  65187. function GeometryBufferRenderer(scene, ratio) {
  65188. if (ratio === void 0) { ratio = 1; }
  65189. this._enablePosition = false;
  65190. this._scene = scene;
  65191. this._ratio = ratio;
  65192. // Render target
  65193. this._createRenderTargets();
  65194. }
  65195. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  65196. /**
  65197. * Set the render list (meshes to be rendered) used in the G buffer.
  65198. */
  65199. set: function (meshes) {
  65200. this._multiRenderTarget.renderList = meshes;
  65201. },
  65202. enumerable: true,
  65203. configurable: true
  65204. });
  65205. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  65206. /**
  65207. * Gets wether or not G buffer are supported by the running hardware.
  65208. * This requires draw buffer supports
  65209. */
  65210. get: function () {
  65211. return this._multiRenderTarget.isSupported;
  65212. },
  65213. enumerable: true,
  65214. configurable: true
  65215. });
  65216. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  65217. /**
  65218. * Gets wether or not position are enabled for the G buffer.
  65219. */
  65220. get: function () {
  65221. return this._enablePosition;
  65222. },
  65223. /**
  65224. * Sets wether or not position are enabled for the G buffer.
  65225. */
  65226. set: function (enable) {
  65227. this._enablePosition = enable;
  65228. this.dispose();
  65229. this._createRenderTargets();
  65230. },
  65231. enumerable: true,
  65232. configurable: true
  65233. });
  65234. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  65235. /**
  65236. * Gets the scene associated with the buffer.
  65237. */
  65238. get: function () {
  65239. return this._scene;
  65240. },
  65241. enumerable: true,
  65242. configurable: true
  65243. });
  65244. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  65245. /**
  65246. * Gets the ratio used by the buffer during its creation.
  65247. * How big is the buffer related to the main canvas.
  65248. */
  65249. get: function () {
  65250. return this._ratio;
  65251. },
  65252. enumerable: true,
  65253. configurable: true
  65254. });
  65255. /**
  65256. * Checks wether everything is ready to render a submesh to the G buffer.
  65257. * @param subMesh the submesh to check readiness for
  65258. * @param useInstances is the mesh drawn using instance or not
  65259. * @returns true if ready otherwise false
  65260. */
  65261. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  65262. var material = subMesh.getMaterial();
  65263. if (material && material.disableDepthWrite) {
  65264. return false;
  65265. }
  65266. var defines = [];
  65267. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65268. var mesh = subMesh.getMesh();
  65269. // Alpha test
  65270. if (material && material.needAlphaTesting()) {
  65271. defines.push("#define ALPHATEST");
  65272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65273. attribs.push(BABYLON.VertexBuffer.UVKind);
  65274. defines.push("#define UV1");
  65275. }
  65276. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65277. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65278. defines.push("#define UV2");
  65279. }
  65280. }
  65281. // Buffers
  65282. if (this._enablePosition) {
  65283. defines.push("#define POSITION");
  65284. }
  65285. // Bones
  65286. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65289. if (mesh.numBoneInfluencers > 4) {
  65290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65292. }
  65293. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65294. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65295. }
  65296. else {
  65297. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65298. }
  65299. // Instances
  65300. if (useInstances) {
  65301. defines.push("#define INSTANCES");
  65302. attribs.push("world0");
  65303. attribs.push("world1");
  65304. attribs.push("world2");
  65305. attribs.push("world3");
  65306. }
  65307. // Get correct effect
  65308. var join = defines.join("\n");
  65309. if (this._cachedDefines !== join) {
  65310. this._cachedDefines = join;
  65311. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  65312. }
  65313. return this._effect.isReady();
  65314. };
  65315. /**
  65316. * Gets the current underlying G Buffer.
  65317. * @returns the buffer
  65318. */
  65319. GeometryBufferRenderer.prototype.getGBuffer = function () {
  65320. return this._multiRenderTarget;
  65321. };
  65322. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  65323. /**
  65324. * Gets the number of samples used to render the buffer (anti aliasing).
  65325. */
  65326. get: function () {
  65327. return this._multiRenderTarget.samples;
  65328. },
  65329. /**
  65330. * Sets the number of samples used to render the buffer (anti aliasing).
  65331. */
  65332. set: function (value) {
  65333. this._multiRenderTarget.samples = value;
  65334. },
  65335. enumerable: true,
  65336. configurable: true
  65337. });
  65338. /**
  65339. * Disposes the renderer and frees up associated resources.
  65340. */
  65341. GeometryBufferRenderer.prototype.dispose = function () {
  65342. this.getGBuffer().dispose();
  65343. };
  65344. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  65345. var _this = this;
  65346. var engine = this._scene.getEngine();
  65347. var count = this._enablePosition ? 3 : 2;
  65348. 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 });
  65349. if (!this.isSupported) {
  65350. return;
  65351. }
  65352. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65353. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65354. this._multiRenderTarget.refreshRate = 1;
  65355. this._multiRenderTarget.renderParticles = false;
  65356. this._multiRenderTarget.renderList = null;
  65357. // set default depth value to 1.0 (far away)
  65358. this._multiRenderTarget.onClearObservable.add(function (engine) {
  65359. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  65360. });
  65361. // Custom render function
  65362. var renderSubMesh = function (subMesh) {
  65363. var mesh = subMesh.getRenderingMesh();
  65364. var scene = _this._scene;
  65365. var engine = scene.getEngine();
  65366. var material = subMesh.getMaterial();
  65367. if (!material) {
  65368. return;
  65369. }
  65370. // Culling
  65371. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65372. // Managing instances
  65373. var batch = mesh._getInstancesRenderList(subMesh._id);
  65374. if (batch.mustReturn) {
  65375. return;
  65376. }
  65377. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65378. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  65379. engine.enableEffect(_this._effect);
  65380. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65381. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65382. _this._effect.setMatrix("view", scene.getViewMatrix());
  65383. // Alpha test
  65384. if (material && material.needAlphaTesting()) {
  65385. var alphaTexture = material.getAlphaTestTexture();
  65386. if (alphaTexture) {
  65387. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65388. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65389. }
  65390. }
  65391. // Bones
  65392. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65393. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65394. }
  65395. // Draw
  65396. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65397. }
  65398. };
  65399. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65400. var index;
  65401. if (depthOnlySubMeshes.length) {
  65402. engine.setColorWrite(false);
  65403. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65404. renderSubMesh(depthOnlySubMeshes.data[index]);
  65405. }
  65406. engine.setColorWrite(true);
  65407. }
  65408. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65409. renderSubMesh(opaqueSubMeshes.data[index]);
  65410. }
  65411. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65412. renderSubMesh(alphaTestSubMeshes.data[index]);
  65413. }
  65414. };
  65415. };
  65416. return GeometryBufferRenderer;
  65417. }());
  65418. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  65419. })(BABYLON || (BABYLON = {}));
  65420. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  65421. var BABYLON;
  65422. (function (BABYLON) {
  65423. var RefractionPostProcess = /** @class */ (function (_super) {
  65424. __extends(RefractionPostProcess, _super);
  65425. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  65426. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  65427. _this.color = color;
  65428. _this.depth = depth;
  65429. _this.colorLevel = colorLevel;
  65430. _this.onActivateObservable.add(function (cam) {
  65431. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  65432. });
  65433. _this.onApplyObservable.add(function (effect) {
  65434. effect.setColor3("baseColor", _this.color);
  65435. effect.setFloat("depth", _this.depth);
  65436. effect.setFloat("colorLevel", _this.colorLevel);
  65437. effect.setTexture("refractionSampler", _this._refRexture);
  65438. });
  65439. return _this;
  65440. }
  65441. // Methods
  65442. RefractionPostProcess.prototype.dispose = function (camera) {
  65443. if (this._refRexture) {
  65444. this._refRexture.dispose();
  65445. }
  65446. _super.prototype.dispose.call(this, camera);
  65447. };
  65448. return RefractionPostProcess;
  65449. }(BABYLON.PostProcess));
  65450. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65451. })(BABYLON || (BABYLON = {}));
  65452. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65453. var BABYLON;
  65454. (function (BABYLON) {
  65455. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65456. __extends(BlackAndWhitePostProcess, _super);
  65457. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65458. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65459. _this.degree = 1;
  65460. _this.onApplyObservable.add(function (effect) {
  65461. effect.setFloat("degree", _this.degree);
  65462. });
  65463. return _this;
  65464. }
  65465. return BlackAndWhitePostProcess;
  65466. }(BABYLON.PostProcess));
  65467. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65468. })(BABYLON || (BABYLON = {}));
  65469. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65470. var BABYLON;
  65471. (function (BABYLON) {
  65472. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65473. __extends(ConvolutionPostProcess, _super);
  65474. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65475. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65476. _this.kernel = kernel;
  65477. _this.onApply = function (effect) {
  65478. effect.setFloat2("screenSize", _this.width, _this.height);
  65479. effect.setArray("kernel", _this.kernel);
  65480. };
  65481. return _this;
  65482. }
  65483. // Statics
  65484. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65485. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65486. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65487. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65488. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65489. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65490. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65491. return ConvolutionPostProcess;
  65492. }(BABYLON.PostProcess));
  65493. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65494. })(BABYLON || (BABYLON = {}));
  65495. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65496. var BABYLON;
  65497. (function (BABYLON) {
  65498. var FilterPostProcess = /** @class */ (function (_super) {
  65499. __extends(FilterPostProcess, _super);
  65500. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65501. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65502. _this.kernelMatrix = kernelMatrix;
  65503. _this.onApply = function (effect) {
  65504. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65505. };
  65506. return _this;
  65507. }
  65508. return FilterPostProcess;
  65509. }(BABYLON.PostProcess));
  65510. BABYLON.FilterPostProcess = FilterPostProcess;
  65511. })(BABYLON || (BABYLON = {}));
  65512. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65513. var BABYLON;
  65514. (function (BABYLON) {
  65515. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65516. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65517. __extends(VolumetricLightScatteringPostProcess, _super);
  65518. /**
  65519. * @constructor
  65520. * @param {string} name - The post-process name
  65521. * @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)
  65522. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65523. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65524. * @param {number} samples - The post-process quality, default 100
  65525. * @param {number} samplingMode - The post-process filtering mode
  65526. * @param {BABYLON.Engine} engine - The babylon engine
  65527. * @param {boolean} reusable - If the post-process is reusable
  65528. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65529. */
  65530. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65531. if (samples === void 0) { samples = 100; }
  65532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65533. 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;
  65534. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65535. /**
  65536. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65537. * @type {Vector3}
  65538. */
  65539. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65540. /**
  65541. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65542. * @type {boolean}
  65543. */
  65544. _this.useCustomMeshPosition = false;
  65545. /**
  65546. * If the post-process should inverse the light scattering direction
  65547. * @type {boolean}
  65548. */
  65549. _this.invert = true;
  65550. /**
  65551. * Array containing the excluded meshes not rendered in the internal pass
  65552. */
  65553. _this.excludedMeshes = new Array();
  65554. /**
  65555. * Controls the overall intensity of the post-process
  65556. * @type {number}
  65557. */
  65558. _this.exposure = 0.3;
  65559. /**
  65560. * Dissipates each sample's contribution in range [0, 1]
  65561. * @type {number}
  65562. */
  65563. _this.decay = 0.96815;
  65564. /**
  65565. * Controls the overall intensity of each sample
  65566. * @type {number}
  65567. */
  65568. _this.weight = 0.58767;
  65569. /**
  65570. * Controls the density of each sample
  65571. * @type {number}
  65572. */
  65573. _this.density = 0.926;
  65574. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65575. engine = scene.getEngine();
  65576. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65577. // Configure mesh
  65578. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65579. // Configure
  65580. _this._createPass(scene, ratio.passRatio || ratio);
  65581. _this.onActivate = function (camera) {
  65582. if (!_this.isSupported) {
  65583. _this.dispose(camera);
  65584. }
  65585. _this.onActivate = null;
  65586. };
  65587. _this.onApplyObservable.add(function (effect) {
  65588. _this._updateMeshScreenCoordinates(scene);
  65589. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65590. effect.setFloat("exposure", _this.exposure);
  65591. effect.setFloat("decay", _this.decay);
  65592. effect.setFloat("weight", _this.weight);
  65593. effect.setFloat("density", _this.density);
  65594. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65595. });
  65596. return _this;
  65597. }
  65598. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65599. get: function () {
  65600. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65601. return false;
  65602. },
  65603. set: function (useDiffuseColor) {
  65604. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65605. },
  65606. enumerable: true,
  65607. configurable: true
  65608. });
  65609. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65610. return "VolumetricLightScatteringPostProcess";
  65611. };
  65612. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65613. var mesh = subMesh.getMesh();
  65614. // Render this.mesh as default
  65615. if (mesh === this.mesh && mesh.material) {
  65616. return mesh.material.isReady(mesh);
  65617. }
  65618. var defines = [];
  65619. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65620. var material = subMesh.getMaterial();
  65621. // Alpha test
  65622. if (material) {
  65623. if (material.needAlphaTesting()) {
  65624. defines.push("#define ALPHATEST");
  65625. }
  65626. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65627. attribs.push(BABYLON.VertexBuffer.UVKind);
  65628. defines.push("#define UV1");
  65629. }
  65630. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65631. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65632. defines.push("#define UV2");
  65633. }
  65634. }
  65635. // Bones
  65636. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65640. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65641. }
  65642. else {
  65643. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65644. }
  65645. // Instances
  65646. if (useInstances) {
  65647. defines.push("#define INSTANCES");
  65648. attribs.push("world0");
  65649. attribs.push("world1");
  65650. attribs.push("world2");
  65651. attribs.push("world3");
  65652. }
  65653. // Get correct effect
  65654. var join = defines.join("\n");
  65655. if (this._cachedDefines !== join) {
  65656. this._cachedDefines = join;
  65657. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65658. }
  65659. return this._volumetricLightScatteringPass.isReady();
  65660. };
  65661. /**
  65662. * Sets the new light position for light scattering effect
  65663. * @param {BABYLON.Vector3} The new custom light position
  65664. */
  65665. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65666. this.customMeshPosition = position;
  65667. };
  65668. /**
  65669. * Returns the light position for light scattering effect
  65670. * @return {BABYLON.Vector3} The custom light position
  65671. */
  65672. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65673. return this.customMeshPosition;
  65674. };
  65675. /**
  65676. * Disposes the internal assets and detaches the post-process from the camera
  65677. */
  65678. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65679. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65680. if (rttIndex !== -1) {
  65681. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65682. }
  65683. this._volumetricLightScatteringRTT.dispose();
  65684. _super.prototype.dispose.call(this, camera);
  65685. };
  65686. /**
  65687. * Returns the render target texture used by the post-process
  65688. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65689. */
  65690. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65691. return this._volumetricLightScatteringRTT;
  65692. };
  65693. // Private methods
  65694. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65695. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65696. return true;
  65697. }
  65698. return false;
  65699. };
  65700. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65701. var _this = this;
  65702. var engine = scene.getEngine();
  65703. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65704. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65705. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65706. this._volumetricLightScatteringRTT.renderList = null;
  65707. this._volumetricLightScatteringRTT.renderParticles = false;
  65708. var camera = this.getCamera();
  65709. if (camera) {
  65710. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65711. }
  65712. else {
  65713. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65714. }
  65715. // Custom render function for submeshes
  65716. var renderSubMesh = function (subMesh) {
  65717. var mesh = subMesh.getRenderingMesh();
  65718. if (_this._meshExcluded(mesh)) {
  65719. return;
  65720. }
  65721. var material = subMesh.getMaterial();
  65722. if (!material) {
  65723. return;
  65724. }
  65725. var scene = mesh.getScene();
  65726. var engine = scene.getEngine();
  65727. // Culling
  65728. engine.setState(material.backFaceCulling);
  65729. // Managing instances
  65730. var batch = mesh._getInstancesRenderList(subMesh._id);
  65731. if (batch.mustReturn) {
  65732. return;
  65733. }
  65734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65735. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65736. var effect = _this._volumetricLightScatteringPass;
  65737. if (mesh === _this.mesh) {
  65738. if (subMesh.effect) {
  65739. effect = subMesh.effect;
  65740. }
  65741. else {
  65742. effect = material.getEffect();
  65743. }
  65744. }
  65745. engine.enableEffect(effect);
  65746. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65747. if (mesh === _this.mesh) {
  65748. material.bind(mesh.getWorldMatrix(), mesh);
  65749. }
  65750. else {
  65751. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65752. // Alpha test
  65753. if (material && material.needAlphaTesting()) {
  65754. var alphaTexture = material.getAlphaTestTexture();
  65755. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65756. if (alphaTexture) {
  65757. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65758. }
  65759. }
  65760. // Bones
  65761. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65762. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65763. }
  65764. }
  65765. // Draw
  65766. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65767. }
  65768. };
  65769. // Render target texture callbacks
  65770. var savedSceneClearColor;
  65771. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65772. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65773. savedSceneClearColor = scene.clearColor;
  65774. scene.clearColor = sceneClearColor;
  65775. });
  65776. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65777. scene.clearColor = savedSceneClearColor;
  65778. });
  65779. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65780. var engine = scene.getEngine();
  65781. var index;
  65782. if (depthOnlySubMeshes.length) {
  65783. engine.setColorWrite(false);
  65784. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65785. renderSubMesh(depthOnlySubMeshes.data[index]);
  65786. }
  65787. engine.setColorWrite(true);
  65788. }
  65789. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65790. renderSubMesh(opaqueSubMeshes.data[index]);
  65791. }
  65792. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65793. renderSubMesh(alphaTestSubMeshes.data[index]);
  65794. }
  65795. if (transparentSubMeshes.length) {
  65796. // Sort sub meshes
  65797. for (index = 0; index < transparentSubMeshes.length; index++) {
  65798. var submesh = transparentSubMeshes.data[index];
  65799. var boundingInfo = submesh.getBoundingInfo();
  65800. if (boundingInfo && scene.activeCamera) {
  65801. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65802. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65803. }
  65804. }
  65805. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65806. sortedArray.sort(function (a, b) {
  65807. // Alpha index first
  65808. if (a._alphaIndex > b._alphaIndex) {
  65809. return 1;
  65810. }
  65811. if (a._alphaIndex < b._alphaIndex) {
  65812. return -1;
  65813. }
  65814. // Then distance to camera
  65815. if (a._distanceToCamera < b._distanceToCamera) {
  65816. return 1;
  65817. }
  65818. if (a._distanceToCamera > b._distanceToCamera) {
  65819. return -1;
  65820. }
  65821. return 0;
  65822. });
  65823. // Render sub meshes
  65824. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65825. for (index = 0; index < sortedArray.length; index++) {
  65826. renderSubMesh(sortedArray[index]);
  65827. }
  65828. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65829. }
  65830. };
  65831. };
  65832. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  65833. var transform = scene.getTransformMatrix();
  65834. var meshPosition;
  65835. if (this.useCustomMeshPosition) {
  65836. meshPosition = this.customMeshPosition;
  65837. }
  65838. else if (this.attachedNode) {
  65839. meshPosition = this.attachedNode.position;
  65840. }
  65841. else {
  65842. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  65843. }
  65844. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  65845. this._screenCoordinates.x = pos.x / this._viewPort.width;
  65846. this._screenCoordinates.y = pos.y / this._viewPort.height;
  65847. if (this.invert)
  65848. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  65849. };
  65850. // Static methods
  65851. /**
  65852. * Creates a default mesh for the Volumeric Light Scattering post-process
  65853. * @param {string} The mesh name
  65854. * @param {BABYLON.Scene} The scene where to create the mesh
  65855. * @return {BABYLON.Mesh} the default mesh
  65856. */
  65857. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  65858. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  65859. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  65860. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  65861. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  65862. mesh.material = material;
  65863. return mesh;
  65864. };
  65865. __decorate([
  65866. BABYLON.serializeAsVector3()
  65867. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  65868. __decorate([
  65869. BABYLON.serialize()
  65870. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  65871. __decorate([
  65872. BABYLON.serialize()
  65873. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  65874. __decorate([
  65875. BABYLON.serializeAsMeshReference()
  65876. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  65877. __decorate([
  65878. BABYLON.serialize()
  65879. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  65880. __decorate([
  65881. BABYLON.serialize()
  65882. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  65883. __decorate([
  65884. BABYLON.serialize()
  65885. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  65886. __decorate([
  65887. BABYLON.serialize()
  65888. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  65889. __decorate([
  65890. BABYLON.serialize()
  65891. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  65892. return VolumetricLightScatteringPostProcess;
  65893. }(BABYLON.PostProcess));
  65894. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  65895. })(BABYLON || (BABYLON = {}));
  65896. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  65897. //
  65898. // This post-process allows the modification of rendered colors by using
  65899. // a 'look-up table' (LUT). This effect is also called Color Grading.
  65900. //
  65901. // The object needs to be provided an url to a texture containing the color
  65902. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  65903. // Use an image editing software to tweak the LUT to match your needs.
  65904. //
  65905. // For an example of a color LUT, see here:
  65906. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  65907. // For explanations on color grading, see here:
  65908. // http://udn.epicgames.com/Three/ColorGrading.html
  65909. //
  65910. var BABYLON;
  65911. (function (BABYLON) {
  65912. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  65913. __extends(ColorCorrectionPostProcess, _super);
  65914. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  65915. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  65916. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65917. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  65918. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65919. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65920. _this.onApply = function (effect) {
  65921. effect.setTexture("colorTable", _this._colorTableTexture);
  65922. };
  65923. return _this;
  65924. }
  65925. return ColorCorrectionPostProcess;
  65926. }(BABYLON.PostProcess));
  65927. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  65928. })(BABYLON || (BABYLON = {}));
  65929. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  65930. var BABYLON;
  65931. (function (BABYLON) {
  65932. var TonemappingOperator;
  65933. (function (TonemappingOperator) {
  65934. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  65935. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  65936. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  65937. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  65938. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  65939. ;
  65940. var TonemapPostProcess = /** @class */ (function (_super) {
  65941. __extends(TonemapPostProcess, _super);
  65942. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  65943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65944. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65945. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  65946. _this._operator = _operator;
  65947. _this.exposureAdjustment = exposureAdjustment;
  65948. var defines = "#define ";
  65949. if (_this._operator === TonemappingOperator.Hable)
  65950. defines += "HABLE_TONEMAPPING";
  65951. else if (_this._operator === TonemappingOperator.Reinhard)
  65952. defines += "REINHARD_TONEMAPPING";
  65953. else if (_this._operator === TonemappingOperator.HejiDawson)
  65954. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  65955. else if (_this._operator === TonemappingOperator.Photographic)
  65956. defines += "PHOTOGRAPHIC_TONEMAPPING";
  65957. //sadly a second call to create the effect.
  65958. _this.updateEffect(defines);
  65959. _this.onApply = function (effect) {
  65960. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  65961. };
  65962. return _this;
  65963. }
  65964. return TonemapPostProcess;
  65965. }(BABYLON.PostProcess));
  65966. BABYLON.TonemapPostProcess = TonemapPostProcess;
  65967. })(BABYLON || (BABYLON = {}));
  65968. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  65969. var BABYLON;
  65970. (function (BABYLON) {
  65971. var DisplayPassPostProcess = /** @class */ (function (_super) {
  65972. __extends(DisplayPassPostProcess, _super);
  65973. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  65974. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  65975. }
  65976. return DisplayPassPostProcess;
  65977. }(BABYLON.PostProcess));
  65978. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  65979. })(BABYLON || (BABYLON = {}));
  65980. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  65981. var BABYLON;
  65982. (function (BABYLON) {
  65983. var HighlightsPostProcess = /** @class */ (function (_super) {
  65984. __extends(HighlightsPostProcess, _super);
  65985. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65987. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65988. }
  65989. return HighlightsPostProcess;
  65990. }(BABYLON.PostProcess));
  65991. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  65992. })(BABYLON || (BABYLON = {}));
  65993. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  65994. var BABYLON;
  65995. (function (BABYLON) {
  65996. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  65997. __extends(ImageProcessingPostProcess, _super);
  65998. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  65999. if (camera === void 0) { camera = null; }
  66000. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66001. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  66002. _this._fromLinearSpace = true;
  66003. /**
  66004. * Defines cache preventing GC.
  66005. */
  66006. _this._defines = {
  66007. IMAGEPROCESSING: false,
  66008. VIGNETTE: false,
  66009. VIGNETTEBLENDMODEMULTIPLY: false,
  66010. VIGNETTEBLENDMODEOPAQUE: false,
  66011. TONEMAPPING: false,
  66012. CONTRAST: false,
  66013. COLORCURVES: false,
  66014. COLORGRADING: false,
  66015. COLORGRADING3D: false,
  66016. FROMLINEARSPACE: false,
  66017. SAMPLER3DGREENDEPTH: false,
  66018. SAMPLER3DBGRMAP: false,
  66019. IMAGEPROCESSINGPOSTPROCESS: false,
  66020. EXPOSURE: false,
  66021. };
  66022. // Setup the configuration as forced by the constructor. This would then not force the
  66023. // scene materials output in linear space and let untouched the default forward pass.
  66024. if (imageProcessingConfiguration) {
  66025. imageProcessingConfiguration.applyByPostProcess = true;
  66026. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  66027. // This will cause the shader to be compiled
  66028. _this.fromLinearSpace = false;
  66029. }
  66030. else {
  66031. _this._attachImageProcessingConfiguration(null, true);
  66032. _this.imageProcessingConfiguration.applyByPostProcess = true;
  66033. }
  66034. _this.onApply = function (effect) {
  66035. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  66036. };
  66037. return _this;
  66038. }
  66039. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  66040. /**
  66041. * Gets the image processing configuration used either in this material.
  66042. */
  66043. get: function () {
  66044. return this._imageProcessingConfiguration;
  66045. },
  66046. /**
  66047. * Sets the Default image processing configuration used either in the this material.
  66048. *
  66049. * If sets to null, the scene one is in use.
  66050. */
  66051. set: function (value) {
  66052. this._attachImageProcessingConfiguration(value);
  66053. },
  66054. enumerable: true,
  66055. configurable: true
  66056. });
  66057. /**
  66058. * Attaches a new image processing configuration to the PBR Material.
  66059. * @param configuration
  66060. */
  66061. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  66062. var _this = this;
  66063. if (doNotBuild === void 0) { doNotBuild = false; }
  66064. if (configuration === this._imageProcessingConfiguration) {
  66065. return;
  66066. }
  66067. // Detaches observer.
  66068. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66069. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66070. }
  66071. // Pick the scene configuration if needed.
  66072. if (!configuration) {
  66073. var scene = null;
  66074. var engine = this.getEngine();
  66075. var camera = this.getCamera();
  66076. if (camera) {
  66077. scene = camera.getScene();
  66078. }
  66079. else if (engine && engine.scenes) {
  66080. var scenes = engine.scenes;
  66081. scene = scenes[scenes.length - 1];
  66082. }
  66083. else {
  66084. scene = BABYLON.Engine.LastCreatedScene;
  66085. }
  66086. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  66087. }
  66088. else {
  66089. this._imageProcessingConfiguration = configuration;
  66090. }
  66091. // Attaches observer.
  66092. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  66093. _this._updateParameters();
  66094. });
  66095. // Ensure the effect will be rebuilt.
  66096. if (!doNotBuild) {
  66097. this._updateParameters();
  66098. }
  66099. };
  66100. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  66101. /**
  66102. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  66103. */
  66104. get: function () {
  66105. return this.imageProcessingConfiguration.colorCurves;
  66106. },
  66107. /**
  66108. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  66109. */
  66110. set: function (value) {
  66111. this.imageProcessingConfiguration.colorCurves = value;
  66112. },
  66113. enumerable: true,
  66114. configurable: true
  66115. });
  66116. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  66117. /**
  66118. * Gets wether the color curves effect is enabled.
  66119. */
  66120. get: function () {
  66121. return this.imageProcessingConfiguration.colorCurvesEnabled;
  66122. },
  66123. /**
  66124. * Sets wether the color curves effect is enabled.
  66125. */
  66126. set: function (value) {
  66127. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  66128. },
  66129. enumerable: true,
  66130. configurable: true
  66131. });
  66132. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  66133. /**
  66134. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  66135. */
  66136. get: function () {
  66137. return this.imageProcessingConfiguration.colorGradingTexture;
  66138. },
  66139. /**
  66140. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  66141. */
  66142. set: function (value) {
  66143. this.imageProcessingConfiguration.colorGradingTexture = value;
  66144. },
  66145. enumerable: true,
  66146. configurable: true
  66147. });
  66148. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  66149. /**
  66150. * Gets wether the color grading effect is enabled.
  66151. */
  66152. get: function () {
  66153. return this.imageProcessingConfiguration.colorGradingEnabled;
  66154. },
  66155. /**
  66156. * Gets wether the color grading effect is enabled.
  66157. */
  66158. set: function (value) {
  66159. this.imageProcessingConfiguration.colorGradingEnabled = value;
  66160. },
  66161. enumerable: true,
  66162. configurable: true
  66163. });
  66164. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  66165. /**
  66166. * Gets exposure used in the effect.
  66167. */
  66168. get: function () {
  66169. return this.imageProcessingConfiguration.exposure;
  66170. },
  66171. /**
  66172. * Sets exposure used in the effect.
  66173. */
  66174. set: function (value) {
  66175. this.imageProcessingConfiguration.exposure = value;
  66176. },
  66177. enumerable: true,
  66178. configurable: true
  66179. });
  66180. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  66181. /**
  66182. * Gets wether tonemapping is enabled or not.
  66183. */
  66184. get: function () {
  66185. return this._imageProcessingConfiguration.toneMappingEnabled;
  66186. },
  66187. /**
  66188. * Sets wether tonemapping is enabled or not
  66189. */
  66190. set: function (value) {
  66191. this._imageProcessingConfiguration.toneMappingEnabled = value;
  66192. },
  66193. enumerable: true,
  66194. configurable: true
  66195. });
  66196. ;
  66197. ;
  66198. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  66199. /**
  66200. * Gets contrast used in the effect.
  66201. */
  66202. get: function () {
  66203. return this.imageProcessingConfiguration.contrast;
  66204. },
  66205. /**
  66206. * Sets contrast used in the effect.
  66207. */
  66208. set: function (value) {
  66209. this.imageProcessingConfiguration.contrast = value;
  66210. },
  66211. enumerable: true,
  66212. configurable: true
  66213. });
  66214. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  66215. /**
  66216. * Gets Vignette stretch size.
  66217. */
  66218. get: function () {
  66219. return this.imageProcessingConfiguration.vignetteStretch;
  66220. },
  66221. /**
  66222. * Sets Vignette stretch size.
  66223. */
  66224. set: function (value) {
  66225. this.imageProcessingConfiguration.vignetteStretch = value;
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  66231. /**
  66232. * Gets Vignette centre X Offset.
  66233. */
  66234. get: function () {
  66235. return this.imageProcessingConfiguration.vignetteCentreX;
  66236. },
  66237. /**
  66238. * Sets Vignette centre X Offset.
  66239. */
  66240. set: function (value) {
  66241. this.imageProcessingConfiguration.vignetteCentreX = value;
  66242. },
  66243. enumerable: true,
  66244. configurable: true
  66245. });
  66246. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  66247. /**
  66248. * Gets Vignette centre Y Offset.
  66249. */
  66250. get: function () {
  66251. return this.imageProcessingConfiguration.vignetteCentreY;
  66252. },
  66253. /**
  66254. * Sets Vignette centre Y Offset.
  66255. */
  66256. set: function (value) {
  66257. this.imageProcessingConfiguration.vignetteCentreY = value;
  66258. },
  66259. enumerable: true,
  66260. configurable: true
  66261. });
  66262. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  66263. /**
  66264. * Gets Vignette weight or intensity of the vignette effect.
  66265. */
  66266. get: function () {
  66267. return this.imageProcessingConfiguration.vignetteWeight;
  66268. },
  66269. /**
  66270. * Sets Vignette weight or intensity of the vignette effect.
  66271. */
  66272. set: function (value) {
  66273. this.imageProcessingConfiguration.vignetteWeight = value;
  66274. },
  66275. enumerable: true,
  66276. configurable: true
  66277. });
  66278. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  66279. /**
  66280. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66281. * if vignetteEnabled is set to true.
  66282. */
  66283. get: function () {
  66284. return this.imageProcessingConfiguration.vignetteColor;
  66285. },
  66286. /**
  66287. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66288. * if vignetteEnabled is set to true.
  66289. */
  66290. set: function (value) {
  66291. this.imageProcessingConfiguration.vignetteColor = value;
  66292. },
  66293. enumerable: true,
  66294. configurable: true
  66295. });
  66296. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  66297. /**
  66298. * Gets Camera field of view used by the Vignette effect.
  66299. */
  66300. get: function () {
  66301. return this.imageProcessingConfiguration.vignetteCameraFov;
  66302. },
  66303. /**
  66304. * Sets Camera field of view used by the Vignette effect.
  66305. */
  66306. set: function (value) {
  66307. this.imageProcessingConfiguration.vignetteCameraFov = value;
  66308. },
  66309. enumerable: true,
  66310. configurable: true
  66311. });
  66312. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  66313. /**
  66314. * Gets the vignette blend mode allowing different kind of effect.
  66315. */
  66316. get: function () {
  66317. return this.imageProcessingConfiguration.vignetteBlendMode;
  66318. },
  66319. /**
  66320. * Sets the vignette blend mode allowing different kind of effect.
  66321. */
  66322. set: function (value) {
  66323. this.imageProcessingConfiguration.vignetteBlendMode = value;
  66324. },
  66325. enumerable: true,
  66326. configurable: true
  66327. });
  66328. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  66329. /**
  66330. * Gets wether the vignette effect is enabled.
  66331. */
  66332. get: function () {
  66333. return this.imageProcessingConfiguration.vignetteEnabled;
  66334. },
  66335. /**
  66336. * Sets wether the vignette effect is enabled.
  66337. */
  66338. set: function (value) {
  66339. this.imageProcessingConfiguration.vignetteEnabled = value;
  66340. },
  66341. enumerable: true,
  66342. configurable: true
  66343. });
  66344. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  66345. /**
  66346. * Gets wether the input of the processing is in Gamma or Linear Space.
  66347. */
  66348. get: function () {
  66349. return this._fromLinearSpace;
  66350. },
  66351. /**
  66352. * Sets wether the input of the processing is in Gamma or Linear Space.
  66353. */
  66354. set: function (value) {
  66355. if (this._fromLinearSpace === value) {
  66356. return;
  66357. }
  66358. this._fromLinearSpace = value;
  66359. this._updateParameters();
  66360. },
  66361. enumerable: true,
  66362. configurable: true
  66363. });
  66364. ImageProcessingPostProcess.prototype.getClassName = function () {
  66365. return "ImageProcessingPostProcess";
  66366. };
  66367. ImageProcessingPostProcess.prototype._updateParameters = function () {
  66368. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  66369. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  66370. var defines = "";
  66371. for (var define in this._defines) {
  66372. if (this._defines[define]) {
  66373. defines += "#define " + define + ";\r\n";
  66374. }
  66375. }
  66376. var samplers = ["textureSampler"];
  66377. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  66378. var uniforms = ["scale"];
  66379. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  66380. this.updateEffect(defines, uniforms, samplers);
  66381. };
  66382. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  66383. _super.prototype.dispose.call(this, camera);
  66384. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66385. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66386. }
  66387. this.imageProcessingConfiguration.applyByPostProcess = false;
  66388. };
  66389. __decorate([
  66390. BABYLON.serialize()
  66391. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  66392. return ImageProcessingPostProcess;
  66393. }(BABYLON.PostProcess));
  66394. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  66395. })(BABYLON || (BABYLON = {}));
  66396. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  66397. var BABYLON;
  66398. (function (BABYLON) {
  66399. /**
  66400. * The Blur Post Process which blurs an image based on a kernel and direction.
  66401. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  66402. */
  66403. var BlurPostProcess = /** @class */ (function (_super) {
  66404. __extends(BlurPostProcess, _super);
  66405. /**
  66406. * Creates a new instance of @see BlurPostProcess
  66407. * @param name The name of the effect.
  66408. * @param direction The direction in which to blur the image.
  66409. * @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.
  66410. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66411. * @param camera The camera to apply the render pass to.
  66412. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66413. * @param engine The engine which the post process will be applied. (default: current engine)
  66414. * @param reusable If the post process can be reused on the same frame. (default: false)
  66415. * @param textureType Type of textures used when performing the post process. (default: 0)
  66416. */
  66417. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  66418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66419. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66420. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  66421. _this.direction = direction;
  66422. _this._packedFloat = false;
  66423. _this._staticDefines = "";
  66424. _this.onApplyObservable.add(function (effect) {
  66425. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  66426. });
  66427. _this.kernel = kernel;
  66428. return _this;
  66429. }
  66430. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  66431. /**
  66432. * Gets the length in pixels of the blur sample region
  66433. */
  66434. get: function () {
  66435. return this._idealKernel;
  66436. },
  66437. /**
  66438. * Sets the length in pixels of the blur sample region
  66439. */
  66440. set: function (v) {
  66441. if (this._idealKernel === v) {
  66442. return;
  66443. }
  66444. v = Math.max(v, 1);
  66445. this._idealKernel = v;
  66446. this._kernel = this._nearestBestKernel(v);
  66447. this._updateParameters();
  66448. },
  66449. enumerable: true,
  66450. configurable: true
  66451. });
  66452. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  66453. /**
  66454. * Gets wether or not the blur is unpacking/repacking floats
  66455. */
  66456. get: function () {
  66457. return this._packedFloat;
  66458. },
  66459. /**
  66460. * Sets wether or not the blur needs to unpack/repack floats
  66461. */
  66462. set: function (v) {
  66463. if (this._packedFloat === v) {
  66464. return;
  66465. }
  66466. this._packedFloat = v;
  66467. this._updateParameters();
  66468. },
  66469. enumerable: true,
  66470. configurable: true
  66471. });
  66472. BlurPostProcess.prototype._updateParameters = function () {
  66473. // Generate sampling offsets and weights
  66474. var N = this._kernel;
  66475. var centerIndex = (N - 1) / 2;
  66476. // Generate Gaussian sampling weights over kernel
  66477. var offsets = [];
  66478. var weights = [];
  66479. var totalWeight = 0;
  66480. for (var i = 0; i < N; i++) {
  66481. var u = i / (N - 1);
  66482. var w = this._gaussianWeight(u * 2.0 - 1);
  66483. offsets[i] = (i - centerIndex);
  66484. weights[i] = w;
  66485. totalWeight += w;
  66486. }
  66487. // Normalize weights
  66488. for (var i = 0; i < weights.length; i++) {
  66489. weights[i] /= totalWeight;
  66490. }
  66491. // Optimize: combine samples to take advantage of hardware linear sampling
  66492. // Walk from left to center, combining pairs (symmetrically)
  66493. var linearSamplingWeights = [];
  66494. var linearSamplingOffsets = [];
  66495. var linearSamplingMap = [];
  66496. for (var i = 0; i <= centerIndex; i += 2) {
  66497. var j = Math.min(i + 1, Math.floor(centerIndex));
  66498. var singleCenterSample = i === j;
  66499. if (singleCenterSample) {
  66500. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66501. }
  66502. else {
  66503. var sharedCell = j === centerIndex;
  66504. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66505. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66506. if (offsetLinear === 0) {
  66507. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66508. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66509. }
  66510. else {
  66511. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66512. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66513. }
  66514. }
  66515. }
  66516. for (var i = 0; i < linearSamplingMap.length; i++) {
  66517. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66518. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66519. }
  66520. // Replace with optimized
  66521. offsets = linearSamplingOffsets;
  66522. weights = linearSamplingWeights;
  66523. // Generate shaders
  66524. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66525. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66526. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66527. var defines = "";
  66528. defines += this._staticDefines;
  66529. for (var i = 0; i < varyingCount; i++) {
  66530. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66531. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66532. }
  66533. var depCount = 0;
  66534. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66535. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66536. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66537. depCount++;
  66538. }
  66539. if (this.packedFloat) {
  66540. defines += "#define PACKEDFLOAT 1";
  66541. }
  66542. this.updateEffect(defines, null, null, {
  66543. varyingCount: varyingCount,
  66544. depCount: depCount
  66545. });
  66546. };
  66547. /**
  66548. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66549. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66550. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66551. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66552. * The gaps between physical kernels are compensated for in the weighting of the samples
  66553. * @param idealKernel Ideal blur kernel.
  66554. * @return Nearest best kernel.
  66555. */
  66556. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66557. var v = Math.round(idealKernel);
  66558. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66559. var k = _a[_i];
  66560. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66561. return Math.max(k, 3);
  66562. }
  66563. }
  66564. return Math.max(v, 3);
  66565. };
  66566. /**
  66567. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66568. * @param x The point on the Gaussian distribution to sample.
  66569. * @return the value of the Gaussian function at x.
  66570. */
  66571. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66572. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66573. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66574. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66575. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66576. // truncated at around 1.3% of peak strength.
  66577. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66578. var sigma = (1 / 3);
  66579. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66580. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66581. var weight = (1.0 / denominator) * Math.exp(exponent);
  66582. return weight;
  66583. };
  66584. /**
  66585. * Generates a string that can be used as a floating point number in GLSL.
  66586. * @param x Value to print.
  66587. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66588. * @return GLSL float string.
  66589. */
  66590. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66591. if (decimalFigures === void 0) { decimalFigures = 8; }
  66592. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66593. };
  66594. return BlurPostProcess;
  66595. }(BABYLON.PostProcess));
  66596. BABYLON.BlurPostProcess = BlurPostProcess;
  66597. })(BABYLON || (BABYLON = {}));
  66598. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66599. var BABYLON;
  66600. (function (BABYLON) {
  66601. var Bone = /** @class */ (function (_super) {
  66602. __extends(Bone, _super);
  66603. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66604. if (parentBone === void 0) { parentBone = null; }
  66605. if (localMatrix === void 0) { localMatrix = null; }
  66606. if (restPose === void 0) { restPose = null; }
  66607. if (baseMatrix === void 0) { baseMatrix = null; }
  66608. if (index === void 0) { index = null; }
  66609. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66610. _this.name = name;
  66611. _this.children = new Array();
  66612. _this.animations = new Array();
  66613. // Set this value to map this bone to a different index in the transform matrices.
  66614. // Set this value to -1 to exclude the bone from the transform matrices.
  66615. _this._index = null;
  66616. _this._worldTransform = new BABYLON.Matrix();
  66617. _this._absoluteTransform = new BABYLON.Matrix();
  66618. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66619. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66620. _this._scaleVector = BABYLON.Vector3.One();
  66621. _this._negateScaleChildren = BABYLON.Vector3.One();
  66622. _this._scalingDeterminant = 1;
  66623. _this._skeleton = skeleton;
  66624. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66625. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66626. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66627. _this._index = index;
  66628. skeleton.bones.push(_this);
  66629. _this.setParent(parentBone, false);
  66630. _this._updateDifferenceMatrix();
  66631. return _this;
  66632. }
  66633. Object.defineProperty(Bone.prototype, "_matrix", {
  66634. get: function () {
  66635. return this._localMatrix;
  66636. },
  66637. set: function (val) {
  66638. if (this._localMatrix) {
  66639. this._localMatrix.copyFrom(val);
  66640. }
  66641. else {
  66642. this._localMatrix = val;
  66643. }
  66644. },
  66645. enumerable: true,
  66646. configurable: true
  66647. });
  66648. // Members
  66649. Bone.prototype.getSkeleton = function () {
  66650. return this._skeleton;
  66651. };
  66652. Bone.prototype.getParent = function () {
  66653. return this._parent;
  66654. };
  66655. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66656. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66657. if (this._parent === parent) {
  66658. return;
  66659. }
  66660. if (this._parent) {
  66661. var index = this._parent.children.indexOf(this);
  66662. if (index !== -1) {
  66663. this._parent.children.splice(index, 1);
  66664. }
  66665. }
  66666. this._parent = parent;
  66667. if (this._parent) {
  66668. this._parent.children.push(this);
  66669. }
  66670. if (updateDifferenceMatrix) {
  66671. this._updateDifferenceMatrix();
  66672. }
  66673. };
  66674. Bone.prototype.getLocalMatrix = function () {
  66675. return this._localMatrix;
  66676. };
  66677. Bone.prototype.getBaseMatrix = function () {
  66678. return this._baseMatrix;
  66679. };
  66680. Bone.prototype.getRestPose = function () {
  66681. return this._restPose;
  66682. };
  66683. Bone.prototype.returnToRest = function () {
  66684. this.updateMatrix(this._restPose.clone());
  66685. };
  66686. Bone.prototype.getWorldMatrix = function () {
  66687. return this._worldTransform;
  66688. };
  66689. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66690. return this._invertedAbsoluteTransform;
  66691. };
  66692. Bone.prototype.getAbsoluteTransform = function () {
  66693. return this._absoluteTransform;
  66694. };
  66695. Object.defineProperty(Bone.prototype, "position", {
  66696. // Properties (matches AbstractMesh properties)
  66697. get: function () {
  66698. return this.getPosition();
  66699. },
  66700. set: function (newPosition) {
  66701. this.setPosition(newPosition);
  66702. },
  66703. enumerable: true,
  66704. configurable: true
  66705. });
  66706. Object.defineProperty(Bone.prototype, "rotation", {
  66707. get: function () {
  66708. return this.getRotation();
  66709. },
  66710. set: function (newRotation) {
  66711. this.setRotation(newRotation);
  66712. },
  66713. enumerable: true,
  66714. configurable: true
  66715. });
  66716. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66717. get: function () {
  66718. return this.getRotationQuaternion();
  66719. },
  66720. set: function (newRotation) {
  66721. this.setRotationQuaternion(newRotation);
  66722. },
  66723. enumerable: true,
  66724. configurable: true
  66725. });
  66726. Object.defineProperty(Bone.prototype, "scaling", {
  66727. get: function () {
  66728. return this.getScale();
  66729. },
  66730. set: function (newScaling) {
  66731. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66732. },
  66733. enumerable: true,
  66734. configurable: true
  66735. });
  66736. // Methods
  66737. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66738. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66739. this._baseMatrix = matrix.clone();
  66740. this._localMatrix = matrix.clone();
  66741. this._skeleton._markAsDirty();
  66742. if (updateDifferenceMatrix) {
  66743. this._updateDifferenceMatrix();
  66744. }
  66745. };
  66746. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66747. if (!rootMatrix) {
  66748. rootMatrix = this._baseMatrix;
  66749. }
  66750. if (this._parent) {
  66751. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66752. }
  66753. else {
  66754. this._absoluteTransform.copyFrom(rootMatrix);
  66755. }
  66756. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66757. for (var index = 0; index < this.children.length; index++) {
  66758. this.children[index]._updateDifferenceMatrix();
  66759. }
  66760. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  66761. };
  66762. Bone.prototype.markAsDirty = function () {
  66763. this._currentRenderId++;
  66764. this._skeleton._markAsDirty();
  66765. };
  66766. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  66767. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66768. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  66769. // all animation may be coming from a library skeleton, so may need to create animation
  66770. if (this.animations.length === 0) {
  66771. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  66772. this.animations[0].setKeys([]);
  66773. }
  66774. // get animation info / verify there is such a range from the source bone
  66775. var sourceRange = source.animations[0].getRange(rangeName);
  66776. if (!sourceRange) {
  66777. return false;
  66778. }
  66779. var from = sourceRange.from;
  66780. var to = sourceRange.to;
  66781. var sourceKeys = source.animations[0].getKeys();
  66782. // rescaling prep
  66783. var sourceBoneLength = source.length;
  66784. var sourceParent = source.getParent();
  66785. var parent = this.getParent();
  66786. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  66787. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  66788. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  66789. var destKeys = this.animations[0].getKeys();
  66790. // loop vars declaration
  66791. var orig;
  66792. var origTranslation;
  66793. var mat;
  66794. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  66795. orig = sourceKeys[key];
  66796. if (orig.frame >= from && orig.frame <= to) {
  66797. if (rescaleAsRequired) {
  66798. mat = orig.value.clone();
  66799. // scale based on parent ratio, when bone has parent
  66800. if (parentScalingReqd) {
  66801. origTranslation = mat.getTranslation();
  66802. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  66803. // scale based on skeleton dimension ratio when root bone, and value is passed
  66804. }
  66805. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  66806. origTranslation = mat.getTranslation();
  66807. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  66808. // use original when root bone, and no data for skelDimensionsRatio
  66809. }
  66810. else {
  66811. mat = orig.value;
  66812. }
  66813. }
  66814. else {
  66815. mat = orig.value;
  66816. }
  66817. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  66818. }
  66819. }
  66820. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  66821. return true;
  66822. };
  66823. /**
  66824. * Translate the bone in local or world space.
  66825. * @param vec The amount to translate the bone.
  66826. * @param space The space that the translation is in.
  66827. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66828. */
  66829. Bone.prototype.translate = function (vec, space, mesh) {
  66830. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66831. var lm = this.getLocalMatrix();
  66832. if (space == BABYLON.Space.LOCAL) {
  66833. lm.m[12] += vec.x;
  66834. lm.m[13] += vec.y;
  66835. lm.m[14] += vec.z;
  66836. }
  66837. else {
  66838. var wm = null;
  66839. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66840. if (mesh) {
  66841. wm = mesh.getWorldMatrix();
  66842. }
  66843. this._skeleton.computeAbsoluteTransforms();
  66844. var tmat = Bone._tmpMats[0];
  66845. var tvec = Bone._tmpVecs[0];
  66846. if (this._parent) {
  66847. if (mesh && wm) {
  66848. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66849. tmat.multiplyToRef(wm, tmat);
  66850. }
  66851. else {
  66852. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66853. }
  66854. }
  66855. tmat.m[12] = 0;
  66856. tmat.m[13] = 0;
  66857. tmat.m[14] = 0;
  66858. tmat.invert();
  66859. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  66860. lm.m[12] += tvec.x;
  66861. lm.m[13] += tvec.y;
  66862. lm.m[14] += tvec.z;
  66863. }
  66864. this.markAsDirty();
  66865. };
  66866. /**
  66867. * Set the postion of the bone in local or world space.
  66868. * @param position The position to set the bone.
  66869. * @param space The space that the position is in.
  66870. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66871. */
  66872. Bone.prototype.setPosition = function (position, space, mesh) {
  66873. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66874. var lm = this.getLocalMatrix();
  66875. if (space == BABYLON.Space.LOCAL) {
  66876. lm.m[12] = position.x;
  66877. lm.m[13] = position.y;
  66878. lm.m[14] = position.z;
  66879. }
  66880. else {
  66881. var wm = null;
  66882. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66883. if (mesh) {
  66884. wm = mesh.getWorldMatrix();
  66885. }
  66886. this._skeleton.computeAbsoluteTransforms();
  66887. var tmat = Bone._tmpMats[0];
  66888. var vec = Bone._tmpVecs[0];
  66889. if (this._parent) {
  66890. if (mesh && wm) {
  66891. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66892. tmat.multiplyToRef(wm, tmat);
  66893. }
  66894. else {
  66895. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66896. }
  66897. }
  66898. tmat.invert();
  66899. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  66900. lm.m[12] = vec.x;
  66901. lm.m[13] = vec.y;
  66902. lm.m[14] = vec.z;
  66903. }
  66904. this.markAsDirty();
  66905. };
  66906. /**
  66907. * Set the absolute postion of the bone (world space).
  66908. * @param position The position to set the bone.
  66909. * @param mesh The mesh that this bone is attached to.
  66910. */
  66911. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  66912. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  66913. };
  66914. /**
  66915. * Set the scale of the bone on the x, y and z axes.
  66916. * @param x The scale of the bone on the x axis.
  66917. * @param x The scale of the bone on the y axis.
  66918. * @param z The scale of the bone on the z axis.
  66919. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66920. */
  66921. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  66922. if (scaleChildren === void 0) { scaleChildren = false; }
  66923. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  66924. if (!scaleChildren) {
  66925. this._negateScaleChildren.x = 1 / x;
  66926. this._negateScaleChildren.y = 1 / y;
  66927. this._negateScaleChildren.z = 1 / z;
  66928. }
  66929. this._syncScaleVector();
  66930. }
  66931. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  66932. };
  66933. /**
  66934. * Scale the bone on the x, y and z axes.
  66935. * @param x The amount to scale the bone on the x axis.
  66936. * @param x The amount to scale the bone on the y axis.
  66937. * @param z The amount to scale the bone on the z axis.
  66938. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66939. */
  66940. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  66941. if (scaleChildren === void 0) { scaleChildren = false; }
  66942. var locMat = this.getLocalMatrix();
  66943. var origLocMat = Bone._tmpMats[0];
  66944. origLocMat.copyFrom(locMat);
  66945. var origLocMatInv = Bone._tmpMats[1];
  66946. origLocMatInv.copyFrom(origLocMat);
  66947. origLocMatInv.invert();
  66948. var scaleMat = Bone._tmpMats[2];
  66949. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  66950. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  66951. this._scaleVector.x *= x;
  66952. this._scaleVector.y *= y;
  66953. this._scaleVector.z *= z;
  66954. locMat.multiplyToRef(origLocMatInv, locMat);
  66955. locMat.multiplyToRef(scaleMat, locMat);
  66956. locMat.multiplyToRef(origLocMat, locMat);
  66957. var parent = this.getParent();
  66958. if (parent) {
  66959. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  66960. }
  66961. else {
  66962. this.getAbsoluteTransform().copyFrom(locMat);
  66963. }
  66964. var len = this.children.length;
  66965. scaleMat.invert();
  66966. for (var i = 0; i < len; i++) {
  66967. var child = this.children[i];
  66968. var cm = child.getLocalMatrix();
  66969. cm.multiplyToRef(scaleMat, cm);
  66970. var lm = child.getLocalMatrix();
  66971. lm.m[12] *= x;
  66972. lm.m[13] *= y;
  66973. lm.m[14] *= z;
  66974. }
  66975. this.computeAbsoluteTransforms();
  66976. if (scaleChildren) {
  66977. for (var i = 0; i < len; i++) {
  66978. this.children[i].scale(x, y, z, scaleChildren);
  66979. }
  66980. }
  66981. this.markAsDirty();
  66982. };
  66983. /**
  66984. * Set the yaw, pitch, and roll of the bone in local or world space.
  66985. * @param yaw The rotation of the bone on the y axis.
  66986. * @param pitch The rotation of the bone on the x axis.
  66987. * @param roll The rotation of the bone on the z axis.
  66988. * @param space The space that the axes of rotation are in.
  66989. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66990. */
  66991. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  66992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66993. var rotMat = Bone._tmpMats[0];
  66994. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  66995. var rotMatInv = Bone._tmpMats[1];
  66996. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66997. rotMatInv.multiplyToRef(rotMat, rotMat);
  66998. this._rotateWithMatrix(rotMat, space, mesh);
  66999. };
  67000. /**
  67001. * Rotate the bone on an axis in local or world space.
  67002. * @param axis The axis to rotate the bone on.
  67003. * @param amount The amount to rotate the bone.
  67004. * @param space The space that the axis is in.
  67005. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67006. */
  67007. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  67008. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67009. var rmat = Bone._tmpMats[0];
  67010. rmat.m[12] = 0;
  67011. rmat.m[13] = 0;
  67012. rmat.m[14] = 0;
  67013. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  67014. this._rotateWithMatrix(rmat, space, mesh);
  67015. };
  67016. /**
  67017. * Set the rotation of the bone to a particular axis angle in local or world space.
  67018. * @param axis The axis to rotate the bone on.
  67019. * @param angle The angle that the bone should be rotated to.
  67020. * @param space The space that the axis is in.
  67021. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67022. */
  67023. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  67024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67025. var rotMat = Bone._tmpMats[0];
  67026. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  67027. var rotMatInv = Bone._tmpMats[1];
  67028. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67029. rotMatInv.multiplyToRef(rotMat, rotMat);
  67030. this._rotateWithMatrix(rotMat, space, mesh);
  67031. };
  67032. /**
  67033. * Set the euler rotation of the bone in local of world space.
  67034. * @param rotation The euler rotation that the bone should be set to.
  67035. * @param space The space that the rotation is in.
  67036. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67037. */
  67038. Bone.prototype.setRotation = function (rotation, space, mesh) {
  67039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67040. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  67041. };
  67042. /**
  67043. * Set the quaternion rotation of the bone in local of world space.
  67044. * @param quat The quaternion rotation that the bone should be set to.
  67045. * @param space The space that the rotation is in.
  67046. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67047. */
  67048. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  67049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67050. var rotMatInv = Bone._tmpMats[0];
  67051. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67052. var rotMat = Bone._tmpMats[1];
  67053. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  67054. rotMatInv.multiplyToRef(rotMat, rotMat);
  67055. this._rotateWithMatrix(rotMat, space, mesh);
  67056. };
  67057. /**
  67058. * Set the rotation matrix of the bone in local of world space.
  67059. * @param rotMat The rotation matrix that the bone should be set to.
  67060. * @param space The space that the rotation is in.
  67061. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67062. */
  67063. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  67064. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67065. var rotMatInv = Bone._tmpMats[0];
  67066. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67067. var rotMat2 = Bone._tmpMats[1];
  67068. rotMat2.copyFrom(rotMat);
  67069. rotMatInv.multiplyToRef(rotMat, rotMat2);
  67070. this._rotateWithMatrix(rotMat2, space, mesh);
  67071. };
  67072. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  67073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67074. var lmat = this.getLocalMatrix();
  67075. var lx = lmat.m[12];
  67076. var ly = lmat.m[13];
  67077. var lz = lmat.m[14];
  67078. var parent = this.getParent();
  67079. var parentScale = Bone._tmpMats[3];
  67080. var parentScaleInv = Bone._tmpMats[4];
  67081. if (parent) {
  67082. if (space == BABYLON.Space.WORLD) {
  67083. if (mesh) {
  67084. parentScale.copyFrom(mesh.getWorldMatrix());
  67085. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  67086. }
  67087. else {
  67088. parentScale.copyFrom(parent.getAbsoluteTransform());
  67089. }
  67090. }
  67091. else {
  67092. parentScale = parent._scaleMatrix;
  67093. }
  67094. parentScaleInv.copyFrom(parentScale);
  67095. parentScaleInv.invert();
  67096. lmat.multiplyToRef(parentScale, lmat);
  67097. lmat.multiplyToRef(rmat, lmat);
  67098. lmat.multiplyToRef(parentScaleInv, lmat);
  67099. }
  67100. else {
  67101. if (space == BABYLON.Space.WORLD && mesh) {
  67102. parentScale.copyFrom(mesh.getWorldMatrix());
  67103. parentScaleInv.copyFrom(parentScale);
  67104. parentScaleInv.invert();
  67105. lmat.multiplyToRef(parentScale, lmat);
  67106. lmat.multiplyToRef(rmat, lmat);
  67107. lmat.multiplyToRef(parentScaleInv, lmat);
  67108. }
  67109. else {
  67110. lmat.multiplyToRef(rmat, lmat);
  67111. }
  67112. }
  67113. lmat.m[12] = lx;
  67114. lmat.m[13] = ly;
  67115. lmat.m[14] = lz;
  67116. this.computeAbsoluteTransforms();
  67117. this.markAsDirty();
  67118. };
  67119. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  67120. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67121. if (space == BABYLON.Space.WORLD) {
  67122. var scaleMatrix = Bone._tmpMats[2];
  67123. scaleMatrix.copyFrom(this._scaleMatrix);
  67124. rotMatInv.copyFrom(this.getAbsoluteTransform());
  67125. if (mesh) {
  67126. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  67127. var meshScale = Bone._tmpMats[3];
  67128. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  67129. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  67130. }
  67131. rotMatInv.invert();
  67132. scaleMatrix.m[0] *= this._scalingDeterminant;
  67133. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  67134. }
  67135. else {
  67136. rotMatInv.copyFrom(this.getLocalMatrix());
  67137. rotMatInv.invert();
  67138. var scaleMatrix = Bone._tmpMats[2];
  67139. scaleMatrix.copyFrom(this._scaleMatrix);
  67140. if (this._parent) {
  67141. var pscaleMatrix = Bone._tmpMats[3];
  67142. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  67143. pscaleMatrix.invert();
  67144. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  67145. }
  67146. else {
  67147. scaleMatrix.m[0] *= this._scalingDeterminant;
  67148. }
  67149. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  67150. }
  67151. };
  67152. /**
  67153. * Get the scale of the bone
  67154. * @returns the scale of the bone
  67155. */
  67156. Bone.prototype.getScale = function () {
  67157. return this._scaleVector.clone();
  67158. };
  67159. /**
  67160. * Copy the scale of the bone to a vector3.
  67161. * @param result The vector3 to copy the scale to
  67162. */
  67163. Bone.prototype.getScaleToRef = function (result) {
  67164. result.copyFrom(this._scaleVector);
  67165. };
  67166. /**
  67167. * Get the position of the bone in local or world space.
  67168. * @param space The space that the returned position is in.
  67169. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67170. * @returns The position of the bone
  67171. */
  67172. Bone.prototype.getPosition = function (space, mesh) {
  67173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67174. if (mesh === void 0) { mesh = null; }
  67175. var pos = BABYLON.Vector3.Zero();
  67176. this.getPositionToRef(space, mesh, pos);
  67177. return pos;
  67178. };
  67179. /**
  67180. * Copy the position of the bone to a vector3 in local or world space.
  67181. * @param space The space that the returned position is in.
  67182. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67183. * @param result The vector3 to copy the position to.
  67184. */
  67185. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  67186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67187. if (space == BABYLON.Space.LOCAL) {
  67188. var lm = this.getLocalMatrix();
  67189. result.x = lm.m[12];
  67190. result.y = lm.m[13];
  67191. result.z = lm.m[14];
  67192. }
  67193. else {
  67194. var wm = null;
  67195. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67196. if (mesh) {
  67197. wm = mesh.getWorldMatrix();
  67198. }
  67199. this._skeleton.computeAbsoluteTransforms();
  67200. var tmat = Bone._tmpMats[0];
  67201. if (mesh && wm) {
  67202. tmat.copyFrom(this.getAbsoluteTransform());
  67203. tmat.multiplyToRef(wm, tmat);
  67204. }
  67205. else {
  67206. tmat = this.getAbsoluteTransform();
  67207. }
  67208. result.x = tmat.m[12];
  67209. result.y = tmat.m[13];
  67210. result.z = tmat.m[14];
  67211. }
  67212. };
  67213. /**
  67214. * Get the absolute position of the bone (world space).
  67215. * @param mesh The mesh that this bone is attached to.
  67216. * @returns The absolute position of the bone
  67217. */
  67218. Bone.prototype.getAbsolutePosition = function (mesh) {
  67219. if (mesh === void 0) { mesh = null; }
  67220. var pos = BABYLON.Vector3.Zero();
  67221. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  67222. return pos;
  67223. };
  67224. /**
  67225. * Copy the absolute position of the bone (world space) to the result param.
  67226. * @param mesh The mesh that this bone is attached to.
  67227. * @param result The vector3 to copy the absolute position to.
  67228. */
  67229. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  67230. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  67231. };
  67232. /**
  67233. * Compute the absolute transforms of this bone and its children.
  67234. */
  67235. Bone.prototype.computeAbsoluteTransforms = function () {
  67236. if (this._parent) {
  67237. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  67238. }
  67239. else {
  67240. this._absoluteTransform.copyFrom(this._localMatrix);
  67241. var poseMatrix = this._skeleton.getPoseMatrix();
  67242. if (poseMatrix) {
  67243. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  67244. }
  67245. }
  67246. var children = this.children;
  67247. var len = children.length;
  67248. for (var i = 0; i < len; i++) {
  67249. children[i].computeAbsoluteTransforms();
  67250. }
  67251. };
  67252. Bone.prototype._syncScaleVector = function () {
  67253. var lm = this.getLocalMatrix();
  67254. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  67255. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  67256. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  67257. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  67258. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  67259. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  67260. this._scaleVector.x = xs * Math.sqrt(xsq);
  67261. this._scaleVector.y = ys * Math.sqrt(ysq);
  67262. this._scaleVector.z = zs * Math.sqrt(zsq);
  67263. if (this._parent) {
  67264. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  67265. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  67266. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  67267. }
  67268. 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);
  67269. };
  67270. /**
  67271. * Get the world direction from an axis that is in the local space of the bone.
  67272. * @param localAxis The local direction that is used to compute the world direction.
  67273. * @param mesh The mesh that this bone is attached to.
  67274. * @returns The world direction
  67275. */
  67276. Bone.prototype.getDirection = function (localAxis, mesh) {
  67277. if (mesh === void 0) { mesh = null; }
  67278. var result = BABYLON.Vector3.Zero();
  67279. this.getDirectionToRef(localAxis, mesh, result);
  67280. return result;
  67281. };
  67282. /**
  67283. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  67284. * @param localAxis The local direction that is used to compute the world direction.
  67285. * @param mesh The mesh that this bone is attached to.
  67286. * @param result The vector3 that the world direction will be copied to.
  67287. */
  67288. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  67289. if (mesh === void 0) { mesh = null; }
  67290. var wm = null;
  67291. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67292. if (mesh) {
  67293. wm = mesh.getWorldMatrix();
  67294. }
  67295. this._skeleton.computeAbsoluteTransforms();
  67296. var mat = Bone._tmpMats[0];
  67297. mat.copyFrom(this.getAbsoluteTransform());
  67298. if (mesh && wm) {
  67299. mat.multiplyToRef(wm, mat);
  67300. }
  67301. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  67302. result.normalize();
  67303. };
  67304. /**
  67305. * Get the euler rotation of the bone in local or world space.
  67306. * @param space The space that the rotation should be in.
  67307. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67308. * @returns The euler rotation
  67309. */
  67310. Bone.prototype.getRotation = function (space, mesh) {
  67311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67312. if (mesh === void 0) { mesh = null; }
  67313. var result = BABYLON.Vector3.Zero();
  67314. this.getRotationToRef(space, mesh, result);
  67315. return result;
  67316. };
  67317. /**
  67318. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  67319. * @param space The space that the rotation should be in.
  67320. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67321. * @param result The vector3 that the rotation should be copied to.
  67322. */
  67323. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  67324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67325. if (mesh === void 0) { mesh = null; }
  67326. var quat = Bone._tmpQuat;
  67327. this.getRotationQuaternionToRef(space, mesh, quat);
  67328. quat.toEulerAnglesToRef(result);
  67329. };
  67330. /**
  67331. * Get the quaternion rotation of the bone in either local or world space.
  67332. * @param space The space that the rotation should be in.
  67333. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67334. * @returns The quaternion rotation
  67335. */
  67336. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  67337. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67338. if (mesh === void 0) { mesh = null; }
  67339. var result = BABYLON.Quaternion.Identity();
  67340. this.getRotationQuaternionToRef(space, mesh, result);
  67341. return result;
  67342. };
  67343. /**
  67344. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  67345. * @param space The space that the rotation should be in.
  67346. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67347. * @param result The quaternion that the rotation should be copied to.
  67348. */
  67349. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  67350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67351. if (mesh === void 0) { mesh = null; }
  67352. if (space == BABYLON.Space.LOCAL) {
  67353. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67354. }
  67355. else {
  67356. var mat = Bone._tmpMats[0];
  67357. var amat = this.getAbsoluteTransform();
  67358. if (mesh) {
  67359. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67360. }
  67361. else {
  67362. mat.copyFrom(amat);
  67363. }
  67364. mat.m[0] *= this._scalingDeterminant;
  67365. mat.m[1] *= this._scalingDeterminant;
  67366. mat.m[2] *= this._scalingDeterminant;
  67367. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67368. }
  67369. };
  67370. /**
  67371. * Get the rotation matrix of the bone in local or world space.
  67372. * @param space The space that the rotation should be in.
  67373. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67374. * @returns The rotation matrix
  67375. */
  67376. Bone.prototype.getRotationMatrix = function (space, mesh) {
  67377. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67378. var result = BABYLON.Matrix.Identity();
  67379. this.getRotationMatrixToRef(space, mesh, result);
  67380. return result;
  67381. };
  67382. /**
  67383. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  67384. * @param space The space that the rotation should be in.
  67385. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67386. * @param result The quaternion that the rotation should be copied to.
  67387. */
  67388. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  67389. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67390. if (space == BABYLON.Space.LOCAL) {
  67391. this.getLocalMatrix().getRotationMatrixToRef(result);
  67392. }
  67393. else {
  67394. var mat = Bone._tmpMats[0];
  67395. var amat = this.getAbsoluteTransform();
  67396. if (mesh) {
  67397. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67398. }
  67399. else {
  67400. mat.copyFrom(amat);
  67401. }
  67402. mat.m[0] *= this._scalingDeterminant;
  67403. mat.m[1] *= this._scalingDeterminant;
  67404. mat.m[2] *= this._scalingDeterminant;
  67405. mat.getRotationMatrixToRef(result);
  67406. }
  67407. };
  67408. /**
  67409. * Get the world position of a point that is in the local space of the bone.
  67410. * @param position The local position
  67411. * @param mesh The mesh that this bone is attached to.
  67412. * @returns The world position
  67413. */
  67414. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  67415. if (mesh === void 0) { mesh = null; }
  67416. var result = BABYLON.Vector3.Zero();
  67417. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  67418. return result;
  67419. };
  67420. /**
  67421. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  67422. * @param position The local position
  67423. * @param mesh The mesh that this bone is attached to.
  67424. * @param result The vector3 that the world position should be copied to.
  67425. */
  67426. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  67427. if (mesh === void 0) { mesh = null; }
  67428. var wm = null;
  67429. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67430. if (mesh) {
  67431. wm = mesh.getWorldMatrix();
  67432. }
  67433. this._skeleton.computeAbsoluteTransforms();
  67434. var tmat = Bone._tmpMats[0];
  67435. if (mesh && wm) {
  67436. tmat.copyFrom(this.getAbsoluteTransform());
  67437. tmat.multiplyToRef(wm, tmat);
  67438. }
  67439. else {
  67440. tmat = this.getAbsoluteTransform();
  67441. }
  67442. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67443. };
  67444. /**
  67445. * Get the local position of a point that is in world space.
  67446. * @param position The world position
  67447. * @param mesh The mesh that this bone is attached to.
  67448. * @returns The local position
  67449. */
  67450. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  67451. if (mesh === void 0) { mesh = null; }
  67452. var result = BABYLON.Vector3.Zero();
  67453. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  67454. return result;
  67455. };
  67456. /**
  67457. * Get the local position of a point that is in world space and copy it to the result param.
  67458. * @param position The world position
  67459. * @param mesh The mesh that this bone is attached to.
  67460. * @param result The vector3 that the local position should be copied to.
  67461. */
  67462. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67463. if (mesh === void 0) { mesh = null; }
  67464. var wm = null;
  67465. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67466. if (mesh) {
  67467. wm = mesh.getWorldMatrix();
  67468. }
  67469. this._skeleton.computeAbsoluteTransforms();
  67470. var tmat = Bone._tmpMats[0];
  67471. tmat.copyFrom(this.getAbsoluteTransform());
  67472. if (mesh && wm) {
  67473. tmat.multiplyToRef(wm, tmat);
  67474. }
  67475. tmat.invert();
  67476. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67477. };
  67478. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67479. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67480. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67481. return Bone;
  67482. }(BABYLON.Node));
  67483. BABYLON.Bone = Bone;
  67484. })(BABYLON || (BABYLON = {}));
  67485. //# sourceMappingURL=babylon.bone.js.map
  67486. var BABYLON;
  67487. (function (BABYLON) {
  67488. var BoneIKController = /** @class */ (function () {
  67489. function BoneIKController(mesh, bone, options) {
  67490. this.targetPosition = BABYLON.Vector3.Zero();
  67491. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67492. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67493. this.poleAngle = 0;
  67494. this.slerpAmount = 1;
  67495. this._bone1Quat = BABYLON.Quaternion.Identity();
  67496. this._bone1Mat = BABYLON.Matrix.Identity();
  67497. this._bone2Ang = Math.PI;
  67498. this._maxAngle = Math.PI;
  67499. this._rightHandedSystem = false;
  67500. this._bendAxis = BABYLON.Vector3.Right();
  67501. this._slerping = false;
  67502. this._adjustRoll = 0;
  67503. this._bone2 = bone;
  67504. this._bone1 = bone.getParent();
  67505. if (!this._bone1) {
  67506. return;
  67507. }
  67508. this.mesh = mesh;
  67509. var bonePos = bone.getPosition();
  67510. if (bone.getAbsoluteTransform().determinant() > 0) {
  67511. this._rightHandedSystem = true;
  67512. this._bendAxis.x = 0;
  67513. this._bendAxis.y = 0;
  67514. this._bendAxis.z = -1;
  67515. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67516. this._adjustRoll = Math.PI * .5;
  67517. this._bendAxis.z = 1;
  67518. }
  67519. }
  67520. if (this._bone1.length) {
  67521. var boneScale1 = this._bone1.getScale();
  67522. var boneScale2 = this._bone2.getScale();
  67523. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67524. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67525. }
  67526. else if (this._bone1.children[0]) {
  67527. mesh.computeWorldMatrix(true);
  67528. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67529. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67530. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67531. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67532. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67533. }
  67534. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67535. this.maxAngle = Math.PI;
  67536. if (options) {
  67537. if (options.targetMesh) {
  67538. this.targetMesh = options.targetMesh;
  67539. this.targetMesh.computeWorldMatrix(true);
  67540. }
  67541. if (options.poleTargetMesh) {
  67542. this.poleTargetMesh = options.poleTargetMesh;
  67543. this.poleTargetMesh.computeWorldMatrix(true);
  67544. }
  67545. else if (options.poleTargetBone) {
  67546. this.poleTargetBone = options.poleTargetBone;
  67547. }
  67548. else if (this._bone1.getParent()) {
  67549. this.poleTargetBone = this._bone1.getParent();
  67550. }
  67551. if (options.poleTargetLocalOffset) {
  67552. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67553. }
  67554. if (options.poleAngle) {
  67555. this.poleAngle = options.poleAngle;
  67556. }
  67557. if (options.bendAxis) {
  67558. this._bendAxis.copyFrom(options.bendAxis);
  67559. }
  67560. if (options.maxAngle) {
  67561. this.maxAngle = options.maxAngle;
  67562. }
  67563. if (options.slerpAmount) {
  67564. this.slerpAmount = options.slerpAmount;
  67565. }
  67566. }
  67567. }
  67568. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67569. get: function () {
  67570. return this._maxAngle;
  67571. },
  67572. set: function (value) {
  67573. this._setMaxAngle(value);
  67574. },
  67575. enumerable: true,
  67576. configurable: true
  67577. });
  67578. BoneIKController.prototype._setMaxAngle = function (ang) {
  67579. if (ang < 0) {
  67580. ang = 0;
  67581. }
  67582. if (ang > Math.PI || ang == undefined) {
  67583. ang = Math.PI;
  67584. }
  67585. this._maxAngle = ang;
  67586. var a = this._bone1Length;
  67587. var b = this._bone2Length;
  67588. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67589. };
  67590. BoneIKController.prototype.update = function () {
  67591. var bone1 = this._bone1;
  67592. if (!bone1) {
  67593. return;
  67594. }
  67595. var target = this.targetPosition;
  67596. var poleTarget = this.poleTargetPosition;
  67597. var mat1 = BoneIKController._tmpMats[0];
  67598. var mat2 = BoneIKController._tmpMats[1];
  67599. if (this.targetMesh) {
  67600. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67601. }
  67602. if (this.poleTargetBone) {
  67603. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67604. }
  67605. else if (this.poleTargetMesh) {
  67606. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67607. }
  67608. var bonePos = BoneIKController._tmpVecs[0];
  67609. var zaxis = BoneIKController._tmpVecs[1];
  67610. var xaxis = BoneIKController._tmpVecs[2];
  67611. var yaxis = BoneIKController._tmpVecs[3];
  67612. var upAxis = BoneIKController._tmpVecs[4];
  67613. var _tmpQuat = BoneIKController._tmpQuat;
  67614. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67615. poleTarget.subtractToRef(bonePos, upAxis);
  67616. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67617. upAxis.y = 1;
  67618. }
  67619. else {
  67620. upAxis.normalize();
  67621. }
  67622. target.subtractToRef(bonePos, yaxis);
  67623. yaxis.normalize();
  67624. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67625. zaxis.normalize();
  67626. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67627. xaxis.normalize();
  67628. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67629. var a = this._bone1Length;
  67630. var b = this._bone2Length;
  67631. var c = BABYLON.Vector3.Distance(bonePos, target);
  67632. if (this._maxReach > 0) {
  67633. c = Math.min(this._maxReach, c);
  67634. }
  67635. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67636. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67637. if (acosa > 1) {
  67638. acosa = 1;
  67639. }
  67640. if (acosb > 1) {
  67641. acosb = 1;
  67642. }
  67643. if (acosa < -1) {
  67644. acosa = -1;
  67645. }
  67646. if (acosb < -1) {
  67647. acosb = -1;
  67648. }
  67649. var angA = Math.acos(acosa);
  67650. var angB = Math.acos(acosb);
  67651. var angC = -angA - angB;
  67652. if (this._rightHandedSystem) {
  67653. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67654. mat2.multiplyToRef(mat1, mat1);
  67655. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67656. mat2.multiplyToRef(mat1, mat1);
  67657. }
  67658. else {
  67659. var _tmpVec = BoneIKController._tmpVecs[5];
  67660. _tmpVec.copyFrom(this._bendAxis);
  67661. _tmpVec.x *= -1;
  67662. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67663. mat2.multiplyToRef(mat1, mat1);
  67664. }
  67665. if (this.poleAngle) {
  67666. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67667. mat1.multiplyToRef(mat2, mat1);
  67668. }
  67669. if (this._bone1) {
  67670. if (this.slerpAmount < 1) {
  67671. if (!this._slerping) {
  67672. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67673. }
  67674. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67675. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67676. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67677. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67678. this._slerping = true;
  67679. }
  67680. else {
  67681. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67682. this._bone1Mat.copyFrom(mat1);
  67683. this._slerping = false;
  67684. }
  67685. }
  67686. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67687. this._bone2Ang = angC;
  67688. };
  67689. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67690. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67691. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67692. return BoneIKController;
  67693. }());
  67694. BABYLON.BoneIKController = BoneIKController;
  67695. })(BABYLON || (BABYLON = {}));
  67696. //# sourceMappingURL=babylon.boneIKController.js.map
  67697. var BABYLON;
  67698. (function (BABYLON) {
  67699. var BoneLookController = /** @class */ (function () {
  67700. /**
  67701. * Create a BoneLookController
  67702. * @param mesh the mesh that the bone belongs to
  67703. * @param bone the bone that will be looking to the target
  67704. * @param target the target Vector3 to look at
  67705. * @param settings optional settings:
  67706. * - maxYaw: the maximum angle the bone will yaw to
  67707. * - minYaw: the minimum angle the bone will yaw to
  67708. * - maxPitch: the maximum angle the bone will pitch to
  67709. * - minPitch: the minimum angle the bone will yaw to
  67710. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67711. * - upAxis: the up axis of the coordinate system
  67712. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67713. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67714. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67715. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67716. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67717. * - adjustRoll: used to make an adjustment to the roll of the bone
  67718. **/
  67719. function BoneLookController(mesh, bone, target, options) {
  67720. /**
  67721. * The up axis of the coordinate system that is used when the bone is rotated.
  67722. */
  67723. this.upAxis = BABYLON.Vector3.Up();
  67724. /**
  67725. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67726. */
  67727. this.upAxisSpace = BABYLON.Space.LOCAL;
  67728. /**
  67729. * Used to make an adjustment to the yaw of the bone.
  67730. */
  67731. this.adjustYaw = 0;
  67732. /**
  67733. * Used to make an adjustment to the pitch of the bone.
  67734. */
  67735. this.adjustPitch = 0;
  67736. /**
  67737. * Used to make an adjustment to the roll of the bone.
  67738. */
  67739. this.adjustRoll = 0;
  67740. /**
  67741. * 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).
  67742. */
  67743. this.slerpAmount = 1;
  67744. this._boneQuat = BABYLON.Quaternion.Identity();
  67745. this._slerping = false;
  67746. this._firstFrameSkipped = false;
  67747. this._fowardAxis = BABYLON.Vector3.Forward();
  67748. this.mesh = mesh;
  67749. this.bone = bone;
  67750. this.target = target;
  67751. if (options) {
  67752. if (options.adjustYaw) {
  67753. this.adjustYaw = options.adjustYaw;
  67754. }
  67755. if (options.adjustPitch) {
  67756. this.adjustPitch = options.adjustPitch;
  67757. }
  67758. if (options.adjustRoll) {
  67759. this.adjustRoll = options.adjustRoll;
  67760. }
  67761. if (options.maxYaw != null) {
  67762. this.maxYaw = options.maxYaw;
  67763. }
  67764. else {
  67765. this.maxYaw = Math.PI;
  67766. }
  67767. if (options.minYaw != null) {
  67768. this.minYaw = options.minYaw;
  67769. }
  67770. else {
  67771. this.minYaw = -Math.PI;
  67772. }
  67773. if (options.maxPitch != null) {
  67774. this.maxPitch = options.maxPitch;
  67775. }
  67776. else {
  67777. this.maxPitch = Math.PI;
  67778. }
  67779. if (options.minPitch != null) {
  67780. this.minPitch = options.minPitch;
  67781. }
  67782. else {
  67783. this.minPitch = -Math.PI;
  67784. }
  67785. if (options.slerpAmount != null) {
  67786. this.slerpAmount = options.slerpAmount;
  67787. }
  67788. if (options.upAxis != null) {
  67789. this.upAxis = options.upAxis;
  67790. }
  67791. if (options.upAxisSpace != null) {
  67792. this.upAxisSpace = options.upAxisSpace;
  67793. }
  67794. if (options.yawAxis != null || options.pitchAxis != null) {
  67795. var newYawAxis = BABYLON.Axis.Y;
  67796. var newPitchAxis = BABYLON.Axis.X;
  67797. if (options.yawAxis != null) {
  67798. newYawAxis = options.yawAxis.clone();
  67799. newYawAxis.normalize();
  67800. }
  67801. if (options.pitchAxis != null) {
  67802. newPitchAxis = options.pitchAxis.clone();
  67803. newPitchAxis.normalize();
  67804. }
  67805. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  67806. this._transformYawPitch = BABYLON.Matrix.Identity();
  67807. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  67808. this._transformYawPitchInv = this._transformYawPitch.clone();
  67809. this._transformYawPitch.invert();
  67810. }
  67811. }
  67812. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  67813. this.upAxisSpace = BABYLON.Space.LOCAL;
  67814. }
  67815. }
  67816. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  67817. /**
  67818. * Get/set the minimum yaw angle that the bone can look to.
  67819. */
  67820. get: function () {
  67821. return this._minYaw;
  67822. },
  67823. set: function (value) {
  67824. this._minYaw = value;
  67825. this._minYawSin = Math.sin(value);
  67826. this._minYawCos = Math.cos(value);
  67827. if (this._maxYaw != null) {
  67828. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67829. this._yawRange = this._maxYaw - this._minYaw;
  67830. }
  67831. },
  67832. enumerable: true,
  67833. configurable: true
  67834. });
  67835. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  67836. /**
  67837. * Get/set the maximum yaw angle that the bone can look to.
  67838. */
  67839. get: function () {
  67840. return this._maxYaw;
  67841. },
  67842. set: function (value) {
  67843. this._maxYaw = value;
  67844. this._maxYawSin = Math.sin(value);
  67845. this._maxYawCos = Math.cos(value);
  67846. if (this._minYaw != null) {
  67847. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67848. this._yawRange = this._maxYaw - this._minYaw;
  67849. }
  67850. },
  67851. enumerable: true,
  67852. configurable: true
  67853. });
  67854. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  67855. /**
  67856. * Get/set the minimum pitch angle that the bone can look to.
  67857. */
  67858. get: function () {
  67859. return this._minPitch;
  67860. },
  67861. set: function (value) {
  67862. this._minPitch = value;
  67863. this._minPitchTan = Math.tan(value);
  67864. },
  67865. enumerable: true,
  67866. configurable: true
  67867. });
  67868. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  67869. /**
  67870. * Get/set the maximum pitch angle that the bone can look to.
  67871. */
  67872. get: function () {
  67873. return this._maxPitch;
  67874. },
  67875. set: function (value) {
  67876. this._maxPitch = value;
  67877. this._maxPitchTan = Math.tan(value);
  67878. },
  67879. enumerable: true,
  67880. configurable: true
  67881. });
  67882. /**
  67883. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  67884. */
  67885. BoneLookController.prototype.update = function () {
  67886. //skip the first frame when slerping so that the mesh rotation is correct
  67887. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  67888. this._firstFrameSkipped = true;
  67889. return;
  67890. }
  67891. var bone = this.bone;
  67892. var bonePos = BoneLookController._tmpVecs[0];
  67893. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  67894. var target = this.target;
  67895. var _tmpMat1 = BoneLookController._tmpMats[0];
  67896. var _tmpMat2 = BoneLookController._tmpMats[1];
  67897. var mesh = this.mesh;
  67898. var parentBone = bone.getParent();
  67899. var upAxis = BoneLookController._tmpVecs[1];
  67900. upAxis.copyFrom(this.upAxis);
  67901. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  67902. if (this._transformYawPitch) {
  67903. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  67904. }
  67905. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  67906. }
  67907. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  67908. mesh.getDirectionToRef(upAxis, upAxis);
  67909. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  67910. upAxis.normalize();
  67911. }
  67912. }
  67913. var checkYaw = false;
  67914. var checkPitch = false;
  67915. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  67916. checkYaw = true;
  67917. }
  67918. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  67919. checkPitch = true;
  67920. }
  67921. if (checkYaw || checkPitch) {
  67922. var spaceMat = BoneLookController._tmpMats[2];
  67923. var spaceMatInv = BoneLookController._tmpMats[3];
  67924. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  67925. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  67926. }
  67927. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  67928. spaceMat.copyFrom(mesh.getWorldMatrix());
  67929. }
  67930. else {
  67931. var forwardAxis = BoneLookController._tmpVecs[2];
  67932. forwardAxis.copyFrom(this._fowardAxis);
  67933. if (this._transformYawPitch) {
  67934. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  67935. }
  67936. if (parentBone) {
  67937. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  67938. }
  67939. else {
  67940. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  67941. }
  67942. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  67943. rightAxis.normalize();
  67944. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  67945. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  67946. }
  67947. spaceMat.invertToRef(spaceMatInv);
  67948. var xzlen = null;
  67949. if (checkPitch) {
  67950. var localTarget = BoneLookController._tmpVecs[3];
  67951. target.subtractToRef(bonePos, localTarget);
  67952. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67953. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67954. var pitch = Math.atan2(localTarget.y, xzlen);
  67955. var newPitch = pitch;
  67956. if (pitch > this._maxPitch) {
  67957. localTarget.y = this._maxPitchTan * xzlen;
  67958. newPitch = this._maxPitch;
  67959. }
  67960. else if (pitch < this._minPitch) {
  67961. localTarget.y = this._minPitchTan * xzlen;
  67962. newPitch = this._minPitch;
  67963. }
  67964. if (pitch != newPitch) {
  67965. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67966. localTarget.addInPlace(bonePos);
  67967. target = localTarget;
  67968. }
  67969. }
  67970. if (checkYaw) {
  67971. var localTarget = BoneLookController._tmpVecs[4];
  67972. target.subtractToRef(bonePos, localTarget);
  67973. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67974. var yaw = Math.atan2(localTarget.x, localTarget.z);
  67975. var newYaw = yaw;
  67976. if (yaw > this._maxYaw || yaw < this._minYaw) {
  67977. if (xzlen == null) {
  67978. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67979. }
  67980. if (this._yawRange > Math.PI) {
  67981. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  67982. localTarget.z = this._maxYawCos * xzlen;
  67983. localTarget.x = this._maxYawSin * xzlen;
  67984. newYaw = this._maxYaw;
  67985. }
  67986. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  67987. localTarget.z = this._minYawCos * xzlen;
  67988. localTarget.x = this._minYawSin * xzlen;
  67989. newYaw = this._minYaw;
  67990. }
  67991. }
  67992. else {
  67993. if (yaw > this._maxYaw) {
  67994. localTarget.z = this._maxYawCos * xzlen;
  67995. localTarget.x = this._maxYawSin * xzlen;
  67996. newYaw = this._maxYaw;
  67997. }
  67998. else if (yaw < this._minYaw) {
  67999. localTarget.z = this._minYawCos * xzlen;
  68000. localTarget.x = this._minYawSin * xzlen;
  68001. newYaw = this._minYaw;
  68002. }
  68003. }
  68004. }
  68005. if (this._slerping && this._yawRange > Math.PI) {
  68006. //are we going to be crossing into the min/max region?
  68007. var boneFwd = BoneLookController._tmpVecs[8];
  68008. boneFwd.copyFrom(BABYLON.Axis.Z);
  68009. if (this._transformYawPitch) {
  68010. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  68011. }
  68012. var boneRotMat = BoneLookController._tmpMats[4];
  68013. this._boneQuat.toRotationMatrix(boneRotMat);
  68014. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  68015. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  68016. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  68017. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  68018. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  68019. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  68020. if (angBtwTar > angBtwMidYaw) {
  68021. if (xzlen == null) {
  68022. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  68023. }
  68024. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  68025. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  68026. if (angBtwMin < angBtwMax) {
  68027. newYaw = boneYaw + Math.PI * .75;
  68028. localTarget.z = Math.cos(newYaw) * xzlen;
  68029. localTarget.x = Math.sin(newYaw) * xzlen;
  68030. }
  68031. else {
  68032. newYaw = boneYaw - Math.PI * .75;
  68033. localTarget.z = Math.cos(newYaw) * xzlen;
  68034. localTarget.x = Math.sin(newYaw) * xzlen;
  68035. }
  68036. }
  68037. }
  68038. if (yaw != newYaw) {
  68039. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  68040. localTarget.addInPlace(bonePos);
  68041. target = localTarget;
  68042. }
  68043. }
  68044. }
  68045. var zaxis = BoneLookController._tmpVecs[5];
  68046. var xaxis = BoneLookController._tmpVecs[6];
  68047. var yaxis = BoneLookController._tmpVecs[7];
  68048. var _tmpQuat = BoneLookController._tmpQuat;
  68049. target.subtractToRef(bonePos, zaxis);
  68050. zaxis.normalize();
  68051. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  68052. xaxis.normalize();
  68053. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  68054. yaxis.normalize();
  68055. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  68056. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  68057. return;
  68058. }
  68059. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  68060. return;
  68061. }
  68062. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  68063. return;
  68064. }
  68065. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  68066. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  68067. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  68068. }
  68069. if (this.slerpAmount < 1) {
  68070. if (!this._slerping) {
  68071. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  68072. }
  68073. if (this._transformYawPitch) {
  68074. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  68075. }
  68076. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  68077. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  68078. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  68079. this._slerping = true;
  68080. }
  68081. else {
  68082. if (this._transformYawPitch) {
  68083. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  68084. }
  68085. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  68086. this._slerping = false;
  68087. }
  68088. };
  68089. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  68090. var angDiff = ang2 - ang1;
  68091. angDiff %= Math.PI * 2;
  68092. if (angDiff > Math.PI) {
  68093. angDiff -= Math.PI * 2;
  68094. }
  68095. else if (angDiff < -Math.PI) {
  68096. angDiff += Math.PI * 2;
  68097. }
  68098. return angDiff;
  68099. };
  68100. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  68101. ang1 %= (2 * Math.PI);
  68102. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  68103. ang2 %= (2 * Math.PI);
  68104. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  68105. var ab = 0;
  68106. if (ang1 < ang2) {
  68107. ab = ang2 - ang1;
  68108. }
  68109. else {
  68110. ab = ang1 - ang2;
  68111. }
  68112. if (ab > Math.PI) {
  68113. ab = Math.PI * 2 - ab;
  68114. }
  68115. return ab;
  68116. };
  68117. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  68118. ang %= (2 * Math.PI);
  68119. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  68120. ang1 %= (2 * Math.PI);
  68121. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  68122. ang2 %= (2 * Math.PI);
  68123. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  68124. if (ang1 < ang2) {
  68125. if (ang > ang1 && ang < ang2) {
  68126. return true;
  68127. }
  68128. }
  68129. else {
  68130. if (ang > ang2 && ang < ang1) {
  68131. return true;
  68132. }
  68133. }
  68134. return false;
  68135. };
  68136. 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()];
  68137. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  68138. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68139. return BoneLookController;
  68140. }());
  68141. BABYLON.BoneLookController = BoneLookController;
  68142. })(BABYLON || (BABYLON = {}));
  68143. //# sourceMappingURL=babylon.boneLookController.js.map
  68144. var BABYLON;
  68145. (function (BABYLON) {
  68146. var Skeleton = /** @class */ (function () {
  68147. function Skeleton(name, id, scene) {
  68148. this.name = name;
  68149. this.id = id;
  68150. this.bones = new Array();
  68151. this.needInitialSkinMatrix = false;
  68152. this._isDirty = true;
  68153. this._meshesWithPoseMatrix = new Array();
  68154. this._identity = BABYLON.Matrix.Identity();
  68155. this._ranges = {};
  68156. this._lastAbsoluteTransformsUpdateId = -1;
  68157. // Events
  68158. /**
  68159. * An event triggered before computing the skeleton's matrices
  68160. * @type {BABYLON.Observable}
  68161. */
  68162. this.onBeforeComputeObservable = new BABYLON.Observable();
  68163. this.bones = [];
  68164. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68165. scene.skeletons.push(this);
  68166. //make sure it will recalculate the matrix next time prepare is called.
  68167. this._isDirty = true;
  68168. }
  68169. // Members
  68170. Skeleton.prototype.getTransformMatrices = function (mesh) {
  68171. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  68172. return mesh._bonesTransformMatrices;
  68173. }
  68174. if (!this._transformMatrices) {
  68175. this.prepare();
  68176. }
  68177. return this._transformMatrices;
  68178. };
  68179. Skeleton.prototype.getScene = function () {
  68180. return this._scene;
  68181. };
  68182. // Methods
  68183. /**
  68184. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  68185. */
  68186. Skeleton.prototype.toString = function (fullDetails) {
  68187. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  68188. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  68189. if (fullDetails) {
  68190. ret += ", Ranges: {";
  68191. var first = true;
  68192. for (var name_1 in this._ranges) {
  68193. if (first) {
  68194. ret += ", ";
  68195. first = false;
  68196. }
  68197. ret += name_1;
  68198. }
  68199. ret += "}";
  68200. }
  68201. return ret;
  68202. };
  68203. /**
  68204. * Get bone's index searching by name
  68205. * @param {string} name is bone's name to search for
  68206. * @return {number} Indice of the bone. Returns -1 if not found
  68207. */
  68208. Skeleton.prototype.getBoneIndexByName = function (name) {
  68209. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  68210. if (this.bones[boneIndex].name === name) {
  68211. return boneIndex;
  68212. }
  68213. }
  68214. return -1;
  68215. };
  68216. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  68217. // check name not already in use
  68218. if (!this._ranges[name]) {
  68219. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  68220. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68221. if (this.bones[i].animations[0]) {
  68222. this.bones[i].animations[0].createRange(name, from, to);
  68223. }
  68224. }
  68225. }
  68226. };
  68227. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  68228. if (deleteFrames === void 0) { deleteFrames = true; }
  68229. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68230. if (this.bones[i].animations[0]) {
  68231. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  68232. }
  68233. }
  68234. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  68235. };
  68236. Skeleton.prototype.getAnimationRange = function (name) {
  68237. return this._ranges[name];
  68238. };
  68239. /**
  68240. * Returns as an Array, all AnimationRanges defined on this skeleton
  68241. */
  68242. Skeleton.prototype.getAnimationRanges = function () {
  68243. var animationRanges = [];
  68244. var name;
  68245. var i = 0;
  68246. for (name in this._ranges) {
  68247. animationRanges[i] = this._ranges[name];
  68248. i++;
  68249. }
  68250. return animationRanges;
  68251. };
  68252. /**
  68253. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  68254. */
  68255. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  68256. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68257. if (this._ranges[name] || !source.getAnimationRange(name)) {
  68258. return false;
  68259. }
  68260. var ret = true;
  68261. var frameOffset = this._getHighestAnimationFrame() + 1;
  68262. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  68263. var boneDict = {};
  68264. var sourceBones = source.bones;
  68265. var nBones;
  68266. var i;
  68267. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  68268. boneDict[sourceBones[i].name] = sourceBones[i];
  68269. }
  68270. if (this.bones.length !== sourceBones.length) {
  68271. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  68272. ret = false;
  68273. }
  68274. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  68275. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  68276. var boneName = this.bones[i].name;
  68277. var sourceBone = boneDict[boneName];
  68278. if (sourceBone) {
  68279. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  68280. }
  68281. else {
  68282. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  68283. ret = false;
  68284. }
  68285. }
  68286. // do not call createAnimationRange(), since it also is done to bones, which was already done
  68287. var range = source.getAnimationRange(name);
  68288. if (range) {
  68289. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  68290. }
  68291. return ret;
  68292. };
  68293. Skeleton.prototype.returnToRest = function () {
  68294. for (var index = 0; index < this.bones.length; index++) {
  68295. this.bones[index].returnToRest();
  68296. }
  68297. };
  68298. Skeleton.prototype._getHighestAnimationFrame = function () {
  68299. var ret = 0;
  68300. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68301. if (this.bones[i].animations[0]) {
  68302. var highest = this.bones[i].animations[0].getHighestFrame();
  68303. if (ret < highest) {
  68304. ret = highest;
  68305. }
  68306. }
  68307. }
  68308. return ret;
  68309. };
  68310. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  68311. var range = this.getAnimationRange(name);
  68312. if (!range) {
  68313. return null;
  68314. }
  68315. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  68316. };
  68317. Skeleton.prototype._markAsDirty = function () {
  68318. this._isDirty = true;
  68319. };
  68320. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  68321. this._meshesWithPoseMatrix.push(mesh);
  68322. };
  68323. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  68324. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  68325. if (index > -1) {
  68326. this._meshesWithPoseMatrix.splice(index, 1);
  68327. }
  68328. };
  68329. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  68330. this.onBeforeComputeObservable.notifyObservers(this);
  68331. for (var index = 0; index < this.bones.length; index++) {
  68332. var bone = this.bones[index];
  68333. var parentBone = bone.getParent();
  68334. if (parentBone) {
  68335. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  68336. }
  68337. else {
  68338. if (initialSkinMatrix) {
  68339. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  68340. }
  68341. else {
  68342. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  68343. }
  68344. }
  68345. if (bone._index !== -1) {
  68346. var mappedIndex = bone._index === null ? index : bone._index;
  68347. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  68348. }
  68349. }
  68350. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  68351. };
  68352. Skeleton.prototype.prepare = function () {
  68353. if (!this._isDirty) {
  68354. return;
  68355. }
  68356. if (this.needInitialSkinMatrix) {
  68357. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  68358. var mesh = this._meshesWithPoseMatrix[index];
  68359. var poseMatrix = mesh.getPoseMatrix();
  68360. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  68361. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68362. }
  68363. if (this._synchronizedWithMesh !== mesh) {
  68364. this._synchronizedWithMesh = mesh;
  68365. // Prepare bones
  68366. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  68367. var bone = this.bones[boneIndex];
  68368. if (!bone.getParent()) {
  68369. var matrix = bone.getBaseMatrix();
  68370. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  68371. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  68372. }
  68373. }
  68374. }
  68375. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  68376. }
  68377. }
  68378. else {
  68379. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  68380. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68381. }
  68382. this._computeTransformMatrices(this._transformMatrices, null);
  68383. }
  68384. this._isDirty = false;
  68385. this._scene._activeBones.addCount(this.bones.length, false);
  68386. };
  68387. Skeleton.prototype.getAnimatables = function () {
  68388. if (!this._animatables || this._animatables.length !== this.bones.length) {
  68389. this._animatables = [];
  68390. for (var index = 0; index < this.bones.length; index++) {
  68391. this._animatables.push(this.bones[index]);
  68392. }
  68393. }
  68394. return this._animatables;
  68395. };
  68396. Skeleton.prototype.clone = function (name, id) {
  68397. var result = new Skeleton(name, id || name, this._scene);
  68398. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68399. for (var index = 0; index < this.bones.length; index++) {
  68400. var source = this.bones[index];
  68401. var parentBone = null;
  68402. var parent_1 = source.getParent();
  68403. if (parent_1) {
  68404. var parentIndex = this.bones.indexOf(parent_1);
  68405. parentBone = result.bones[parentIndex];
  68406. }
  68407. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  68408. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  68409. }
  68410. if (this._ranges) {
  68411. result._ranges = {};
  68412. for (var rangeName in this._ranges) {
  68413. var range = this._ranges[rangeName];
  68414. if (range) {
  68415. result._ranges[rangeName] = range.clone();
  68416. }
  68417. }
  68418. }
  68419. this._isDirty = true;
  68420. return result;
  68421. };
  68422. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  68423. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  68424. this.bones.forEach(function (bone) {
  68425. bone.animations.forEach(function (animation) {
  68426. animation.enableBlending = true;
  68427. animation.blendingSpeed = blendingSpeed;
  68428. });
  68429. });
  68430. };
  68431. Skeleton.prototype.dispose = function () {
  68432. this._meshesWithPoseMatrix = [];
  68433. // Animations
  68434. this.getScene().stopAnimation(this);
  68435. // Remove from scene
  68436. this.getScene().removeSkeleton(this);
  68437. };
  68438. Skeleton.prototype.serialize = function () {
  68439. var serializationObject = {};
  68440. serializationObject.name = this.name;
  68441. serializationObject.id = this.id;
  68442. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  68443. serializationObject.bones = [];
  68444. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68445. for (var index = 0; index < this.bones.length; index++) {
  68446. var bone = this.bones[index];
  68447. var parent_2 = bone.getParent();
  68448. var serializedBone = {
  68449. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  68450. name: bone.name,
  68451. matrix: bone.getBaseMatrix().toArray(),
  68452. rest: bone.getRestPose().toArray()
  68453. };
  68454. serializationObject.bones.push(serializedBone);
  68455. if (bone.length) {
  68456. serializedBone.length = bone.length;
  68457. }
  68458. if (bone.animations && bone.animations.length > 0) {
  68459. serializedBone.animation = bone.animations[0].serialize();
  68460. }
  68461. serializationObject.ranges = [];
  68462. for (var name in this._ranges) {
  68463. var source = this._ranges[name];
  68464. if (!source) {
  68465. continue;
  68466. }
  68467. var range = {};
  68468. range.name = name;
  68469. range.from = source.from;
  68470. range.to = source.to;
  68471. serializationObject.ranges.push(range);
  68472. }
  68473. }
  68474. return serializationObject;
  68475. };
  68476. Skeleton.Parse = function (parsedSkeleton, scene) {
  68477. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68478. if (parsedSkeleton.dimensionsAtRest) {
  68479. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68480. }
  68481. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68482. var index;
  68483. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68484. var parsedBone = parsedSkeleton.bones[index];
  68485. var parentBone = null;
  68486. if (parsedBone.parentBoneIndex > -1) {
  68487. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68488. }
  68489. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68490. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68491. if (parsedBone.length) {
  68492. bone.length = parsedBone.length;
  68493. }
  68494. if (parsedBone.animation) {
  68495. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68496. }
  68497. }
  68498. // placed after bones, so createAnimationRange can cascade down
  68499. if (parsedSkeleton.ranges) {
  68500. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68501. var data = parsedSkeleton.ranges[index];
  68502. skeleton.createAnimationRange(data.name, data.from, data.to);
  68503. }
  68504. }
  68505. return skeleton;
  68506. };
  68507. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68508. if (forceUpdate === void 0) { forceUpdate = false; }
  68509. var renderId = this._scene.getRenderId();
  68510. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68511. this.bones[0].computeAbsoluteTransforms();
  68512. this._lastAbsoluteTransformsUpdateId = renderId;
  68513. }
  68514. };
  68515. Skeleton.prototype.getPoseMatrix = function () {
  68516. var poseMatrix = null;
  68517. if (this._meshesWithPoseMatrix.length > 0) {
  68518. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68519. }
  68520. return poseMatrix;
  68521. };
  68522. Skeleton.prototype.sortBones = function () {
  68523. var bones = new Array();
  68524. var visited = new Array(this.bones.length);
  68525. for (var index = 0; index < this.bones.length; index++) {
  68526. this._sortBones(index, bones, visited);
  68527. }
  68528. this.bones = bones;
  68529. };
  68530. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68531. if (visited[index]) {
  68532. return;
  68533. }
  68534. visited[index] = true;
  68535. var bone = this.bones[index];
  68536. if (bone._index === undefined) {
  68537. bone._index = index;
  68538. }
  68539. var parentBone = bone.getParent();
  68540. if (parentBone) {
  68541. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68542. }
  68543. bones.push(bone);
  68544. };
  68545. return Skeleton;
  68546. }());
  68547. BABYLON.Skeleton = Skeleton;
  68548. })(BABYLON || (BABYLON = {}));
  68549. //# sourceMappingURL=babylon.skeleton.js.map
  68550. var BABYLON;
  68551. (function (BABYLON) {
  68552. var SphericalPolynomial = /** @class */ (function () {
  68553. function SphericalPolynomial() {
  68554. this.x = BABYLON.Vector3.Zero();
  68555. this.y = BABYLON.Vector3.Zero();
  68556. this.z = BABYLON.Vector3.Zero();
  68557. this.xx = BABYLON.Vector3.Zero();
  68558. this.yy = BABYLON.Vector3.Zero();
  68559. this.zz = BABYLON.Vector3.Zero();
  68560. this.xy = BABYLON.Vector3.Zero();
  68561. this.yz = BABYLON.Vector3.Zero();
  68562. this.zx = BABYLON.Vector3.Zero();
  68563. }
  68564. SphericalPolynomial.prototype.addAmbient = function (color) {
  68565. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68566. this.xx = this.xx.add(colorVector);
  68567. this.yy = this.yy.add(colorVector);
  68568. this.zz = this.zz.add(colorVector);
  68569. };
  68570. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68571. var result = new SphericalPolynomial();
  68572. result.x = harmonics.L11.scale(1.02333);
  68573. result.y = harmonics.L1_1.scale(1.02333);
  68574. result.z = harmonics.L10.scale(1.02333);
  68575. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68576. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68577. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68578. result.yz = harmonics.L2_1.scale(0.858086);
  68579. result.zx = harmonics.L21.scale(0.858086);
  68580. result.xy = harmonics.L2_2.scale(0.858086);
  68581. result.scale(1.0 / Math.PI);
  68582. return result;
  68583. };
  68584. SphericalPolynomial.prototype.scale = function (scale) {
  68585. this.x = this.x.scale(scale);
  68586. this.y = this.y.scale(scale);
  68587. this.z = this.z.scale(scale);
  68588. this.xx = this.xx.scale(scale);
  68589. this.yy = this.yy.scale(scale);
  68590. this.zz = this.zz.scale(scale);
  68591. this.yz = this.yz.scale(scale);
  68592. this.zx = this.zx.scale(scale);
  68593. this.xy = this.xy.scale(scale);
  68594. };
  68595. return SphericalPolynomial;
  68596. }());
  68597. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68598. var SphericalHarmonics = /** @class */ (function () {
  68599. function SphericalHarmonics() {
  68600. this.L00 = BABYLON.Vector3.Zero();
  68601. this.L1_1 = BABYLON.Vector3.Zero();
  68602. this.L10 = BABYLON.Vector3.Zero();
  68603. this.L11 = BABYLON.Vector3.Zero();
  68604. this.L2_2 = BABYLON.Vector3.Zero();
  68605. this.L2_1 = BABYLON.Vector3.Zero();
  68606. this.L20 = BABYLON.Vector3.Zero();
  68607. this.L21 = BABYLON.Vector3.Zero();
  68608. this.L22 = BABYLON.Vector3.Zero();
  68609. }
  68610. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68611. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68612. var c = colorVector.scale(deltaSolidAngle);
  68613. this.L00 = this.L00.add(c.scale(0.282095));
  68614. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68615. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68616. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68617. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68618. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68619. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68620. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68621. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68622. };
  68623. SphericalHarmonics.prototype.scale = function (scale) {
  68624. this.L00 = this.L00.scale(scale);
  68625. this.L1_1 = this.L1_1.scale(scale);
  68626. this.L10 = this.L10.scale(scale);
  68627. this.L11 = this.L11.scale(scale);
  68628. this.L2_2 = this.L2_2.scale(scale);
  68629. this.L2_1 = this.L2_1.scale(scale);
  68630. this.L20 = this.L20.scale(scale);
  68631. this.L21 = this.L21.scale(scale);
  68632. this.L22 = this.L22.scale(scale);
  68633. };
  68634. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68635. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68636. //
  68637. // E_lm = A_l * L_lm
  68638. //
  68639. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68640. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68641. // the scaling factors are given in equation 9.
  68642. // Constant (Band 0)
  68643. this.L00 = this.L00.scale(3.141593);
  68644. // Linear (Band 1)
  68645. this.L1_1 = this.L1_1.scale(2.094395);
  68646. this.L10 = this.L10.scale(2.094395);
  68647. this.L11 = this.L11.scale(2.094395);
  68648. // Quadratic (Band 2)
  68649. this.L2_2 = this.L2_2.scale(0.785398);
  68650. this.L2_1 = this.L2_1.scale(0.785398);
  68651. this.L20 = this.L20.scale(0.785398);
  68652. this.L21 = this.L21.scale(0.785398);
  68653. this.L22 = this.L22.scale(0.785398);
  68654. };
  68655. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68656. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68657. // L = (1/pi) * E * rho
  68658. //
  68659. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68660. this.scale(1.0 / Math.PI);
  68661. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68662. // (The pixel shader must apply albedo after texture fetches, etc).
  68663. };
  68664. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68665. var result = new SphericalHarmonics();
  68666. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68667. result.L1_1 = polynomial.y.scale(0.977204);
  68668. result.L10 = polynomial.z.scale(0.977204);
  68669. result.L11 = polynomial.x.scale(0.977204);
  68670. result.L2_2 = polynomial.xy.scale(1.16538);
  68671. result.L2_1 = polynomial.yz.scale(1.16538);
  68672. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68673. result.L21 = polynomial.zx.scale(1.16538);
  68674. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68675. result.scale(Math.PI);
  68676. return result;
  68677. };
  68678. return SphericalHarmonics;
  68679. }());
  68680. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68681. })(BABYLON || (BABYLON = {}));
  68682. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68683. var BABYLON;
  68684. (function (BABYLON) {
  68685. var FileFaceOrientation = /** @class */ (function () {
  68686. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68687. this.name = name;
  68688. this.worldAxisForNormal = worldAxisForNormal;
  68689. this.worldAxisForFileX = worldAxisForFileX;
  68690. this.worldAxisForFileY = worldAxisForFileY;
  68691. }
  68692. return FileFaceOrientation;
  68693. }());
  68694. ;
  68695. /**
  68696. * Helper class dealing with the extraction of spherical polynomial dataArray
  68697. * from a cube map.
  68698. */
  68699. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68700. function CubeMapToSphericalPolynomialTools() {
  68701. }
  68702. /**
  68703. * Converts a texture to the according Spherical Polynomial data.
  68704. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68705. *
  68706. * @param texture The texture to extract the information from.
  68707. * @return The Spherical Polynomial data.
  68708. */
  68709. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68710. if (!texture.isCube) {
  68711. // Only supports cube Textures currently.
  68712. return null;
  68713. }
  68714. var size = texture.getSize().width;
  68715. var right = texture.readPixels(0);
  68716. var left = texture.readPixels(1);
  68717. var up;
  68718. var down;
  68719. if (texture.isRenderTarget) {
  68720. up = texture.readPixels(3);
  68721. down = texture.readPixels(2);
  68722. }
  68723. else {
  68724. up = texture.readPixels(2);
  68725. down = texture.readPixels(3);
  68726. }
  68727. var front = texture.readPixels(4);
  68728. var back = texture.readPixels(5);
  68729. var gammaSpace = texture.gammaSpace;
  68730. // Always read as RGBA.
  68731. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68732. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68733. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68734. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68735. }
  68736. var cubeInfo = {
  68737. size: size,
  68738. right: right,
  68739. left: left,
  68740. up: up,
  68741. down: down,
  68742. front: front,
  68743. back: back,
  68744. format: format,
  68745. type: type,
  68746. gammaSpace: gammaSpace,
  68747. };
  68748. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68749. };
  68750. /**
  68751. * Converts a cubemap to the according Spherical Polynomial data.
  68752. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68753. *
  68754. * @param cubeInfo The Cube map to extract the information from.
  68755. * @return The Spherical Polynomial data.
  68756. */
  68757. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68758. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68759. var totalSolidAngle = 0.0;
  68760. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  68761. var du = 2.0 / cubeInfo.size;
  68762. var dv = du;
  68763. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  68764. var minUV = du * 0.5 - 1.0;
  68765. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68766. var fileFace = this.FileFaces[faceIndex];
  68767. var dataArray = cubeInfo[fileFace.name];
  68768. var v = minUV;
  68769. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  68770. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  68771. // Because SP is still linear, so summation is fine in that basis.
  68772. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  68773. for (var y = 0; y < cubeInfo.size; y++) {
  68774. var u = minUV;
  68775. for (var x = 0; x < cubeInfo.size; x++) {
  68776. // World direction (not normalised)
  68777. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  68778. worldDirection.normalize();
  68779. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  68780. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  68781. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  68782. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  68783. // Handle Integer types.
  68784. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68785. r /= 255;
  68786. g /= 255;
  68787. b /= 255;
  68788. }
  68789. // Handle Gamma space textures.
  68790. if (cubeInfo.gammaSpace) {
  68791. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  68792. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  68793. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  68794. }
  68795. var color = new BABYLON.Color3(r, g, b);
  68796. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  68797. totalSolidAngle += deltaSolidAngle;
  68798. u += du;
  68799. }
  68800. v += dv;
  68801. }
  68802. }
  68803. // Solid angle for entire sphere is 4*pi
  68804. var sphereSolidAngle = 4.0 * Math.PI;
  68805. // Adjust the solid angle to allow for how many faces we processed.
  68806. var facesProcessed = 6.0;
  68807. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  68808. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  68809. // This is needed because the numerical integration over the cube uses a
  68810. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  68811. // and also to compensate for accumulative error due to float precision in the summation.
  68812. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  68813. sphericalHarmonics.scale(correctionFactor);
  68814. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  68815. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  68816. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  68817. };
  68818. CubeMapToSphericalPolynomialTools.FileFaces = [
  68819. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  68820. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  68821. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  68822. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  68823. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  68824. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  68825. ];
  68826. return CubeMapToSphericalPolynomialTools;
  68827. }());
  68828. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  68829. })(BABYLON || (BABYLON = {}));
  68830. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  68831. var BABYLON;
  68832. (function (BABYLON) {
  68833. /**
  68834. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  68835. */
  68836. var PanoramaToCubeMapTools = /** @class */ (function () {
  68837. function PanoramaToCubeMapTools() {
  68838. }
  68839. /**
  68840. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  68841. *
  68842. * @param float32Array The source data.
  68843. * @param inputWidth The width of the input panorama.
  68844. * @param inputhHeight The height of the input panorama.
  68845. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  68846. * @return The cubemap data
  68847. */
  68848. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  68849. if (!float32Array) {
  68850. throw "ConvertPanoramaToCubemap: input cannot be null";
  68851. }
  68852. if (float32Array.length != inputWidth * inputHeight * 3) {
  68853. throw "ConvertPanoramaToCubemap: input size is wrong";
  68854. }
  68855. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  68856. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  68857. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  68858. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  68859. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  68860. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  68861. return {
  68862. front: textureFront,
  68863. back: textureBack,
  68864. left: textureLeft,
  68865. right: textureRight,
  68866. up: textureUp,
  68867. down: textureDown,
  68868. size: size,
  68869. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  68870. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  68871. gammaSpace: false,
  68872. };
  68873. };
  68874. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  68875. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  68876. var textureArray = new Float32Array(buffer);
  68877. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  68878. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  68879. var dy = 1 / texSize;
  68880. var fy = 0;
  68881. for (var y = 0; y < texSize; y++) {
  68882. var xv1 = faceData[0];
  68883. var xv2 = faceData[2];
  68884. for (var x = 0; x < texSize; x++) {
  68885. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  68886. v.normalize();
  68887. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  68888. // 3 channels per pixels
  68889. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  68890. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  68891. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  68892. xv1 = xv1.add(rotDX1);
  68893. xv2 = xv2.add(rotDX2);
  68894. }
  68895. fy += dy;
  68896. }
  68897. return textureArray;
  68898. };
  68899. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  68900. var theta = Math.atan2(vDir.z, vDir.x);
  68901. var phi = Math.acos(vDir.y);
  68902. while (theta < -Math.PI)
  68903. theta += 2 * Math.PI;
  68904. while (theta > Math.PI)
  68905. theta -= 2 * Math.PI;
  68906. var dx = theta / Math.PI;
  68907. var dy = phi / Math.PI;
  68908. // recenter.
  68909. dx = dx * 0.5 + 0.5;
  68910. var px = Math.round(dx * inputWidth);
  68911. if (px < 0)
  68912. px = 0;
  68913. else if (px >= inputWidth)
  68914. px = inputWidth - 1;
  68915. var py = Math.round(dy * inputHeight);
  68916. if (py < 0)
  68917. py = 0;
  68918. else if (py >= inputHeight)
  68919. py = inputHeight - 1;
  68920. var inputY = (inputHeight - py - 1);
  68921. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  68922. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  68923. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  68924. return {
  68925. r: r,
  68926. g: g,
  68927. b: b
  68928. };
  68929. };
  68930. PanoramaToCubeMapTools.FACE_FRONT = [
  68931. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68932. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68933. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68934. new BABYLON.Vector3(1.0, 1.0, -1.0)
  68935. ];
  68936. PanoramaToCubeMapTools.FACE_BACK = [
  68937. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68938. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68939. new BABYLON.Vector3(1.0, 1.0, 1.0),
  68940. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  68941. ];
  68942. PanoramaToCubeMapTools.FACE_RIGHT = [
  68943. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68944. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68945. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68946. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68947. ];
  68948. PanoramaToCubeMapTools.FACE_LEFT = [
  68949. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68950. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68951. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68952. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  68953. ];
  68954. PanoramaToCubeMapTools.FACE_DOWN = [
  68955. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68956. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68957. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68958. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68959. ];
  68960. PanoramaToCubeMapTools.FACE_UP = [
  68961. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68962. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68963. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68964. new BABYLON.Vector3(1.0, -1.0, -1.0)
  68965. ];
  68966. return PanoramaToCubeMapTools;
  68967. }());
  68968. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  68969. })(BABYLON || (BABYLON = {}));
  68970. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  68971. var BABYLON;
  68972. (function (BABYLON) {
  68973. ;
  68974. /**
  68975. * This groups tools to convert HDR texture to native colors array.
  68976. */
  68977. var HDRTools = /** @class */ (function () {
  68978. function HDRTools() {
  68979. }
  68980. HDRTools.Ldexp = function (mantissa, exponent) {
  68981. if (exponent > 1023) {
  68982. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  68983. }
  68984. if (exponent < -1074) {
  68985. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  68986. }
  68987. return mantissa * Math.pow(2, exponent);
  68988. };
  68989. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  68990. if (exponent > 0) {
  68991. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  68992. float32array[index + 0] = red * exponent;
  68993. float32array[index + 1] = green * exponent;
  68994. float32array[index + 2] = blue * exponent;
  68995. }
  68996. else {
  68997. float32array[index + 0] = 0;
  68998. float32array[index + 1] = 0;
  68999. float32array[index + 2] = 0;
  69000. }
  69001. };
  69002. HDRTools.readStringLine = function (uint8array, startIndex) {
  69003. var line = "";
  69004. var character = "";
  69005. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  69006. character = String.fromCharCode(uint8array[i]);
  69007. if (character == "\n") {
  69008. break;
  69009. }
  69010. line += character;
  69011. }
  69012. return line;
  69013. };
  69014. /**
  69015. * Reads header information from an RGBE texture stored in a native array.
  69016. * More information on this format are available here:
  69017. * https://en.wikipedia.org/wiki/RGBE_image_format
  69018. *
  69019. * @param uint8array The binary file stored in native array.
  69020. * @return The header information.
  69021. */
  69022. HDRTools.RGBE_ReadHeader = function (uint8array) {
  69023. var height = 0;
  69024. var width = 0;
  69025. var line = this.readStringLine(uint8array, 0);
  69026. if (line[0] != '#' || line[1] != '?') {
  69027. throw "Bad HDR Format.";
  69028. }
  69029. var endOfHeader = false;
  69030. var findFormat = false;
  69031. var lineIndex = 0;
  69032. do {
  69033. lineIndex += (line.length + 1);
  69034. line = this.readStringLine(uint8array, lineIndex);
  69035. if (line == "FORMAT=32-bit_rle_rgbe") {
  69036. findFormat = true;
  69037. }
  69038. else if (line.length == 0) {
  69039. endOfHeader = true;
  69040. }
  69041. } while (!endOfHeader);
  69042. if (!findFormat) {
  69043. throw "HDR Bad header format, unsupported FORMAT";
  69044. }
  69045. lineIndex += (line.length + 1);
  69046. line = this.readStringLine(uint8array, lineIndex);
  69047. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  69048. var match = sizeRegexp.exec(line);
  69049. // TODO. Support +Y and -X if needed.
  69050. if (!match || match.length < 3) {
  69051. throw "HDR Bad header format, no size";
  69052. }
  69053. width = parseInt(match[2]);
  69054. height = parseInt(match[1]);
  69055. if (width < 8 || width > 0x7fff) {
  69056. throw "HDR Bad header format, unsupported size";
  69057. }
  69058. lineIndex += (line.length + 1);
  69059. return {
  69060. height: height,
  69061. width: width,
  69062. dataPosition: lineIndex
  69063. };
  69064. };
  69065. /**
  69066. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  69067. * This RGBE texture needs to store the information as a panorama.
  69068. *
  69069. * More information on this format are available here:
  69070. * https://en.wikipedia.org/wiki/RGBE_image_format
  69071. *
  69072. * @param buffer The binary file stored in an array buffer.
  69073. * @param size The expected size of the extracted cubemap.
  69074. * @return The Cube Map information.
  69075. */
  69076. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  69077. var uint8array = new Uint8Array(buffer);
  69078. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  69079. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  69080. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  69081. return cubeMapData;
  69082. };
  69083. /**
  69084. * Returns the pixels data extracted from an RGBE texture.
  69085. * This pixels will be stored left to right up to down in the R G B order in one array.
  69086. *
  69087. * More information on this format are available here:
  69088. * https://en.wikipedia.org/wiki/RGBE_image_format
  69089. *
  69090. * @param uint8array The binary file stored in an array buffer.
  69091. * @param hdrInfo The header information of the file.
  69092. * @return The pixels data in RGB right to left up to down order.
  69093. */
  69094. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  69095. // Keep for multi format supports.
  69096. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  69097. };
  69098. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  69099. var num_scanlines = hdrInfo.height;
  69100. var scanline_width = hdrInfo.width;
  69101. var a, b, c, d, count;
  69102. var dataIndex = hdrInfo.dataPosition;
  69103. var index = 0, endIndex = 0, i = 0;
  69104. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  69105. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  69106. // 3 channels of 4 bytes per pixel in float.
  69107. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  69108. var resultArray = new Float32Array(resultBuffer);
  69109. // read in each successive scanline
  69110. while (num_scanlines > 0) {
  69111. a = uint8array[dataIndex++];
  69112. b = uint8array[dataIndex++];
  69113. c = uint8array[dataIndex++];
  69114. d = uint8array[dataIndex++];
  69115. if (a != 2 || b != 2 || (c & 0x80)) {
  69116. // this file is not run length encoded
  69117. throw "HDR Bad header format, not RLE";
  69118. }
  69119. if (((c << 8) | d) != scanline_width) {
  69120. throw "HDR Bad header format, wrong scan line width";
  69121. }
  69122. index = 0;
  69123. // read each of the four channels for the scanline into the buffer
  69124. for (i = 0; i < 4; i++) {
  69125. endIndex = (i + 1) * scanline_width;
  69126. while (index < endIndex) {
  69127. a = uint8array[dataIndex++];
  69128. b = uint8array[dataIndex++];
  69129. if (a > 128) {
  69130. // a run of the same value
  69131. count = a - 128;
  69132. if ((count == 0) || (count > endIndex - index)) {
  69133. throw "HDR Bad Format, bad scanline data (run)";
  69134. }
  69135. while (count-- > 0) {
  69136. scanLineArray[index++] = b;
  69137. }
  69138. }
  69139. else {
  69140. // a non-run
  69141. count = a;
  69142. if ((count == 0) || (count > endIndex - index)) {
  69143. throw "HDR Bad Format, bad scanline data (non-run)";
  69144. }
  69145. scanLineArray[index++] = b;
  69146. if (--count > 0) {
  69147. for (var j = 0; j < count; j++) {
  69148. scanLineArray[index++] = uint8array[dataIndex++];
  69149. }
  69150. }
  69151. }
  69152. }
  69153. }
  69154. // now convert data from buffer into floats
  69155. for (i = 0; i < scanline_width; i++) {
  69156. a = scanLineArray[i];
  69157. b = scanLineArray[i + scanline_width];
  69158. c = scanLineArray[i + 2 * scanline_width];
  69159. d = scanLineArray[i + 3 * scanline_width];
  69160. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  69161. }
  69162. num_scanlines--;
  69163. }
  69164. return resultArray;
  69165. };
  69166. return HDRTools;
  69167. }());
  69168. BABYLON.HDRTools = HDRTools;
  69169. })(BABYLON || (BABYLON = {}));
  69170. //# sourceMappingURL=babylon.hdr.js.map
  69171. var BABYLON;
  69172. (function (BABYLON) {
  69173. /**
  69174. * This represents a texture coming from an HDR input.
  69175. *
  69176. * The only supported format is currently panorama picture stored in RGBE format.
  69177. * Example of such files can be found on HDRLib: http://hdrlib.com/
  69178. */
  69179. var HDRCubeTexture = /** @class */ (function (_super) {
  69180. __extends(HDRCubeTexture, _super);
  69181. /**
  69182. * Instantiates an HDRTexture from the following parameters.
  69183. *
  69184. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  69185. * @param scene The scene the texture will be used in
  69186. * @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.
  69187. * @param noMipmap Forces to not generate the mipmap if true
  69188. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  69189. * @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)
  69190. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  69191. */
  69192. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  69193. if (noMipmap === void 0) { noMipmap = false; }
  69194. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69195. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69196. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69197. if (onLoad === void 0) { onLoad = null; }
  69198. if (onError === void 0) { onError = null; }
  69199. var _this = _super.call(this, scene) || this;
  69200. _this._useInGammaSpace = false;
  69201. _this._generateHarmonics = true;
  69202. _this._isBABYLONPreprocessed = false;
  69203. _this._onLoad = null;
  69204. _this._onError = null;
  69205. /**
  69206. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  69207. */
  69208. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69209. /**
  69210. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  69211. * This is usefull at run time to apply the good shader.
  69212. */
  69213. _this.isPMREM = false;
  69214. _this._isBlocking = true;
  69215. if (!url) {
  69216. return _this;
  69217. }
  69218. _this.name = url;
  69219. _this.url = url;
  69220. _this.hasAlpha = false;
  69221. _this.isCube = true;
  69222. _this._textureMatrix = BABYLON.Matrix.Identity();
  69223. _this._onLoad = onLoad;
  69224. _this._onError = onError;
  69225. _this.gammaSpace = false;
  69226. var caps = scene.getEngine().getCaps();
  69227. if (size) {
  69228. _this._isBABYLONPreprocessed = false;
  69229. _this._noMipmap = noMipmap;
  69230. _this._size = size;
  69231. _this._useInGammaSpace = useInGammaSpace;
  69232. _this._usePMREMGenerator = usePMREMGenerator &&
  69233. caps.textureLOD &&
  69234. caps.textureFloat &&
  69235. !_this._useInGammaSpace;
  69236. }
  69237. else {
  69238. _this._isBABYLONPreprocessed = true;
  69239. _this._noMipmap = false;
  69240. _this._useInGammaSpace = false;
  69241. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  69242. !_this._useInGammaSpace;
  69243. }
  69244. _this.isPMREM = _this._usePMREMGenerator;
  69245. _this._texture = _this._getFromCache(url, _this._noMipmap);
  69246. if (!_this._texture) {
  69247. if (!scene.useDelayedTextureLoading) {
  69248. _this.loadTexture();
  69249. }
  69250. else {
  69251. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69252. }
  69253. }
  69254. return _this;
  69255. }
  69256. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  69257. /**
  69258. * Gets wether or not the texture is blocking during loading.
  69259. */
  69260. get: function () {
  69261. return this._isBlocking;
  69262. },
  69263. /**
  69264. * Sets wether or not the texture is blocking during loading.
  69265. */
  69266. set: function (value) {
  69267. this._isBlocking = value;
  69268. },
  69269. enumerable: true,
  69270. configurable: true
  69271. });
  69272. /**
  69273. * Occurs when the file is a preprocessed .babylon.hdr file.
  69274. */
  69275. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  69276. var _this = this;
  69277. var mipLevels = 0;
  69278. var floatArrayView = null;
  69279. var scene = this.getScene();
  69280. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  69281. var mips = new Array();
  69282. if (!floatArrayView) {
  69283. return mips;
  69284. }
  69285. var startIndex = 30;
  69286. for (var level = 0; level < mipLevels; level++) {
  69287. mips.push([]);
  69288. // Fill each pixel of the mip level.
  69289. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  69290. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69291. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  69292. mips[level].push(faceData);
  69293. startIndex += faceSize;
  69294. }
  69295. }
  69296. return mips;
  69297. } : null;
  69298. var callback = function (buffer) {
  69299. var scene = _this.getScene();
  69300. if (!scene) {
  69301. return null;
  69302. }
  69303. // Create Native Array Views
  69304. var intArrayView = new Int32Array(buffer);
  69305. floatArrayView = new Float32Array(buffer);
  69306. // Fill header.
  69307. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  69308. _this._size = intArrayView[1]; // CubeMap max mip face size.
  69309. // Update Texture Information.
  69310. if (!_this._texture) {
  69311. return null;
  69312. }
  69313. _this._texture.updateSize(_this._size, _this._size);
  69314. // Fill polynomial information.
  69315. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  69316. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  69317. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  69318. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  69319. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  69320. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  69321. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  69322. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  69323. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  69324. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  69325. _this.sphericalPolynomial = sphericalPolynomial;
  69326. // Fill pixel data.
  69327. mipLevels = intArrayView[29]; // Number of mip levels.
  69328. var startIndex = 30;
  69329. var data = [];
  69330. var faceSize = Math.pow(_this._size, 2) * 3;
  69331. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69332. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  69333. startIndex += faceSize;
  69334. }
  69335. var results = [];
  69336. var byteArray = null;
  69337. // Push each faces.
  69338. for (var k = 0; k < 6; k++) {
  69339. var dataFace = null;
  69340. // To be deprecated.
  69341. if (version === 1) {
  69342. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  69343. dataFace = data[j];
  69344. }
  69345. // If special cases.
  69346. if (!mipmapGenerator && dataFace) {
  69347. if (!scene.getEngine().getCaps().textureFloat) {
  69348. // 3 channels of 1 bytes per pixel in bytes.
  69349. var byteBuffer = new ArrayBuffer(faceSize);
  69350. byteArray = new Uint8Array(byteBuffer);
  69351. }
  69352. for (var i = 0; i < _this._size * _this._size; i++) {
  69353. // Put in gamma space if requested.
  69354. if (_this._useInGammaSpace) {
  69355. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69356. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69357. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69358. }
  69359. // Convert to int texture for fallback.
  69360. if (byteArray) {
  69361. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69362. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69363. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69364. // May use luminance instead if the result is not accurate.
  69365. var max = Math.max(Math.max(r, g), b);
  69366. if (max > 255) {
  69367. var scale = 255 / max;
  69368. r *= scale;
  69369. g *= scale;
  69370. b *= scale;
  69371. }
  69372. byteArray[(i * 3) + 0] = r;
  69373. byteArray[(i * 3) + 1] = g;
  69374. byteArray[(i * 3) + 2] = b;
  69375. }
  69376. }
  69377. }
  69378. // Fill the array accordingly.
  69379. if (byteArray) {
  69380. results.push(byteArray);
  69381. }
  69382. else {
  69383. results.push(dataFace);
  69384. }
  69385. }
  69386. return results;
  69387. };
  69388. if (scene) {
  69389. 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);
  69390. }
  69391. };
  69392. /**
  69393. * Occurs when the file is raw .hdr file.
  69394. */
  69395. HDRCubeTexture.prototype.loadHDRTexture = function () {
  69396. var _this = this;
  69397. var callback = function (buffer) {
  69398. var scene = _this.getScene();
  69399. if (!scene) {
  69400. return null;
  69401. }
  69402. // Extract the raw linear data.
  69403. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  69404. // Generate harmonics if needed.
  69405. if (_this._generateHarmonics) {
  69406. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  69407. _this.sphericalPolynomial = sphericalPolynomial;
  69408. }
  69409. var results = [];
  69410. var byteArray = null;
  69411. // Push each faces.
  69412. for (var j = 0; j < 6; j++) {
  69413. // Create uintarray fallback.
  69414. if (!scene.getEngine().getCaps().textureFloat) {
  69415. // 3 channels of 1 bytes per pixel in bytes.
  69416. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  69417. byteArray = new Uint8Array(byteBuffer);
  69418. }
  69419. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  69420. // If special cases.
  69421. if (_this._useInGammaSpace || byteArray) {
  69422. for (var i = 0; i < _this._size * _this._size; i++) {
  69423. // Put in gamma space if requested.
  69424. if (_this._useInGammaSpace) {
  69425. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69426. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69427. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69428. }
  69429. // Convert to int texture for fallback.
  69430. if (byteArray) {
  69431. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69432. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69433. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69434. // May use luminance instead if the result is not accurate.
  69435. var max = Math.max(Math.max(r, g), b);
  69436. if (max > 255) {
  69437. var scale = 255 / max;
  69438. r *= scale;
  69439. g *= scale;
  69440. b *= scale;
  69441. }
  69442. byteArray[(i * 3) + 0] = r;
  69443. byteArray[(i * 3) + 1] = g;
  69444. byteArray[(i * 3) + 2] = b;
  69445. }
  69446. }
  69447. }
  69448. if (byteArray) {
  69449. results.push(byteArray);
  69450. }
  69451. else {
  69452. results.push(dataFace);
  69453. }
  69454. }
  69455. return results;
  69456. };
  69457. var mipmapGenerator = null;
  69458. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69459. // if (!this._noMipmap &&
  69460. // this._usePMREMGenerator) {
  69461. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69462. // // Custom setup of the generator matching with the PBR shader values.
  69463. // var generator = new BABYLON.PMREMGenerator(data,
  69464. // this._size,
  69465. // this._size,
  69466. // 0,
  69467. // 3,
  69468. // this.getScene().getEngine().getCaps().textureFloat,
  69469. // 2048,
  69470. // 0.25,
  69471. // false,
  69472. // true);
  69473. // return generator.filterCubeMap();
  69474. // };
  69475. // }
  69476. var scene = this.getScene();
  69477. if (scene) {
  69478. 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);
  69479. }
  69480. };
  69481. /**
  69482. * Starts the loading process of the texture.
  69483. */
  69484. HDRCubeTexture.prototype.loadTexture = function () {
  69485. if (this._isBABYLONPreprocessed) {
  69486. this.loadBabylonTexture();
  69487. }
  69488. else {
  69489. this.loadHDRTexture();
  69490. }
  69491. };
  69492. HDRCubeTexture.prototype.clone = function () {
  69493. var scene = this.getScene();
  69494. if (!scene) {
  69495. return this;
  69496. }
  69497. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69498. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69499. // Base texture
  69500. newTexture.level = this.level;
  69501. newTexture.wrapU = this.wrapU;
  69502. newTexture.wrapV = this.wrapV;
  69503. newTexture.coordinatesIndex = this.coordinatesIndex;
  69504. newTexture.coordinatesMode = this.coordinatesMode;
  69505. return newTexture;
  69506. };
  69507. // Methods
  69508. HDRCubeTexture.prototype.delayLoad = function () {
  69509. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69510. return;
  69511. }
  69512. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69513. this._texture = this._getFromCache(this.url, this._noMipmap);
  69514. if (!this._texture) {
  69515. this.loadTexture();
  69516. }
  69517. };
  69518. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69519. return this._textureMatrix;
  69520. };
  69521. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69522. this._textureMatrix = value;
  69523. };
  69524. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69525. var texture = null;
  69526. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69527. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69528. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69529. texture.name = parsedTexture.name;
  69530. texture.hasAlpha = parsedTexture.hasAlpha;
  69531. texture.level = parsedTexture.level;
  69532. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69533. texture.isBlocking = parsedTexture.isBlocking;
  69534. }
  69535. return texture;
  69536. };
  69537. HDRCubeTexture.prototype.serialize = function () {
  69538. if (!this.name) {
  69539. return null;
  69540. }
  69541. var serializationObject = {};
  69542. serializationObject.name = this.name;
  69543. serializationObject.hasAlpha = this.hasAlpha;
  69544. serializationObject.isCube = true;
  69545. serializationObject.level = this.level;
  69546. serializationObject.size = this._size;
  69547. serializationObject.coordinatesMode = this.coordinatesMode;
  69548. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69549. serializationObject.generateHarmonics = this._generateHarmonics;
  69550. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69551. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69552. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69553. serializationObject.noMipmap = this._noMipmap;
  69554. serializationObject.isBlocking = this._isBlocking;
  69555. return serializationObject;
  69556. };
  69557. /**
  69558. * Saves as a file the data contained in the texture in a binary format.
  69559. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69560. * as the spherical used in the lighting.
  69561. * @param url The HDR file url.
  69562. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69563. * @param onError Method called if any error happens during download.
  69564. * @return The packed binary data.
  69565. */
  69566. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69567. if (onError === void 0) { onError = null; }
  69568. var callback = function (buffer) {
  69569. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69570. // Returns a URL you can use as a href.
  69571. var objUrl = window.URL.createObjectURL(data);
  69572. // Simulates a link to it and click to dowload.
  69573. var a = document.createElement("a");
  69574. document.body.appendChild(a);
  69575. a.style.display = "none";
  69576. a.href = objUrl;
  69577. a.download = "envmap.babylon.hdr";
  69578. a.click();
  69579. };
  69580. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69581. };
  69582. /**
  69583. * Serializes the data contained in the texture in a binary format.
  69584. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69585. * as the spherical used in the lighting.
  69586. * @param url The HDR file url.
  69587. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69588. * @param onError Method called if any error happens during download.
  69589. * @return The packed binary data.
  69590. */
  69591. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69592. if (onError === void 0) { onError = null; }
  69593. // Needs the url tho create the texture.
  69594. if (!url) {
  69595. return;
  69596. }
  69597. // Check Power of two size.
  69598. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69599. return;
  69600. }
  69601. // Coming Back in 3.x.
  69602. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69603. };
  69604. HDRCubeTexture._facesMapping = [
  69605. "right",
  69606. "left",
  69607. "up",
  69608. "down",
  69609. "front",
  69610. "back"
  69611. ];
  69612. return HDRCubeTexture;
  69613. }(BABYLON.BaseTexture));
  69614. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69615. })(BABYLON || (BABYLON = {}));
  69616. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69617. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69618. // Huge respect for a such great lib.
  69619. // Earcut license:
  69620. // Copyright (c) 2016, Mapbox
  69621. //
  69622. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69623. // with or without fee is hereby granted, provided that the above copyright notice
  69624. // and this permission notice appear in all copies.
  69625. //
  69626. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69627. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69628. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69629. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69630. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69631. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69632. // THIS SOFTWARE.
  69633. var Earcut;
  69634. (function (Earcut) {
  69635. /**
  69636. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69637. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69638. * @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).
  69639. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69640. */
  69641. function earcut(data, holeIndices, dim) {
  69642. dim = dim || 2;
  69643. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69644. if (!outerNode)
  69645. return triangles;
  69646. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69647. if (hasHoles)
  69648. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69649. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69650. if (data.length > 80 * dim) {
  69651. minX = maxX = data[0];
  69652. minY = maxY = data[1];
  69653. for (var i = dim; i < outerLen; i += dim) {
  69654. x = data[i];
  69655. y = data[i + 1];
  69656. if (x < minX)
  69657. minX = x;
  69658. if (y < minY)
  69659. minY = y;
  69660. if (x > maxX)
  69661. maxX = x;
  69662. if (y > maxY)
  69663. maxY = y;
  69664. }
  69665. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69666. size = Math.max(maxX - minX, maxY - minY);
  69667. }
  69668. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69669. return triangles;
  69670. }
  69671. Earcut.earcut = earcut;
  69672. var Node = /** @class */ (function () {
  69673. function Node(i, x, y) {
  69674. this.i = i;
  69675. this.x = x;
  69676. this.y = y;
  69677. this.prev = null;
  69678. this.next = null;
  69679. this.z = null;
  69680. this.prevZ = null;
  69681. this.nextZ = null;
  69682. this.steiner = false;
  69683. }
  69684. return Node;
  69685. }());
  69686. // create a circular doubly linked list from polygon points in the specified winding order
  69687. function linkedList(data, start, end, dim, clockwise) {
  69688. var i, last = null;
  69689. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69690. for (i = start; i < end; i += dim)
  69691. last = insertNode(i, data[i], data[i + 1], last);
  69692. }
  69693. else {
  69694. for (i = end - dim; i >= start; i -= dim)
  69695. last = insertNode(i, data[i], data[i + 1], last);
  69696. }
  69697. if (last && equals(last, last.next)) {
  69698. removeNode(last);
  69699. last = last.next;
  69700. }
  69701. return last;
  69702. }
  69703. // eliminate colinear or duplicate points
  69704. function filterPoints(start, end) {
  69705. if (!start)
  69706. return start;
  69707. if (!end)
  69708. end = start;
  69709. var p = start, again;
  69710. do {
  69711. again = false;
  69712. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69713. removeNode(p);
  69714. p = end = p.prev;
  69715. if (p === p.next)
  69716. return undefined;
  69717. again = true;
  69718. }
  69719. else {
  69720. p = p.next;
  69721. }
  69722. } while (again || p !== end);
  69723. return end;
  69724. }
  69725. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69726. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69727. if (!ear)
  69728. return;
  69729. // interlink polygon nodes in z-order
  69730. if (!pass && size)
  69731. indexCurve(ear, minX, minY, size);
  69732. var stop = ear, prev, next;
  69733. // iterate through ears, slicing them one by one
  69734. while (ear.prev !== ear.next) {
  69735. prev = ear.prev;
  69736. next = ear.next;
  69737. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69738. // cut off the triangle
  69739. triangles.push(prev.i / dim);
  69740. triangles.push(ear.i / dim);
  69741. triangles.push(next.i / dim);
  69742. removeNode(ear);
  69743. // skipping the next vertice leads to less sliver triangles
  69744. ear = next.next;
  69745. stop = next.next;
  69746. continue;
  69747. }
  69748. ear = next;
  69749. // if we looped through the whole remaining polygon and can't find any more ears
  69750. if (ear === stop) {
  69751. // try filtering points and slicing again
  69752. if (!pass) {
  69753. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69754. // if this didn't work, try curing all small self-intersections locally
  69755. }
  69756. else if (pass === 1) {
  69757. ear = cureLocalIntersections(ear, triangles, dim);
  69758. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69759. // as a last resort, try splitting the remaining polygon into two
  69760. }
  69761. else if (pass === 2) {
  69762. splitEarcut(ear, triangles, dim, minX, minY, size);
  69763. }
  69764. break;
  69765. }
  69766. }
  69767. }
  69768. // check whether a polygon node forms a valid ear with adjacent nodes
  69769. function isEar(ear) {
  69770. var a = ear.prev, b = ear, c = ear.next;
  69771. if (area(a, b, c) >= 0)
  69772. return false; // reflex, can't be an ear
  69773. // now make sure we don't have other points inside the potential ear
  69774. var p = ear.next.next;
  69775. while (p !== ear.prev) {
  69776. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69777. area(p.prev, p, p.next) >= 0)
  69778. return false;
  69779. p = p.next;
  69780. }
  69781. return true;
  69782. }
  69783. function isEarHashed(ear, minX, minY, size) {
  69784. var a = ear.prev, b = ear, c = ear.next;
  69785. if (area(a, b, c) >= 0)
  69786. return false; // reflex, can't be an ear
  69787. // triangle bbox; min & max are calculated like this for speed
  69788. 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);
  69789. // z-order range for the current triangle bbox;
  69790. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  69791. // first look for points inside the triangle in increasing z-order
  69792. var p = ear.nextZ;
  69793. while (p && p.z <= maxZ) {
  69794. if (p !== ear.prev &&
  69795. p !== ear.next &&
  69796. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69797. area(p.prev, p, p.next) >= 0)
  69798. return false;
  69799. p = p.nextZ;
  69800. }
  69801. // then look for points in decreasing z-order
  69802. p = ear.prevZ;
  69803. while (p && p.z >= minZ) {
  69804. if (p !== ear.prev &&
  69805. p !== ear.next &&
  69806. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69807. area(p.prev, p, p.next) >= 0)
  69808. return false;
  69809. p = p.prevZ;
  69810. }
  69811. return true;
  69812. }
  69813. // go through all polygon nodes and cure small local self-intersections
  69814. function cureLocalIntersections(start, triangles, dim) {
  69815. var p = start;
  69816. do {
  69817. var a = p.prev, b = p.next.next;
  69818. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  69819. triangles.push(a.i / dim);
  69820. triangles.push(p.i / dim);
  69821. triangles.push(b.i / dim);
  69822. // remove two nodes involved
  69823. removeNode(p);
  69824. removeNode(p.next);
  69825. p = start = b;
  69826. }
  69827. p = p.next;
  69828. } while (p !== start);
  69829. return p;
  69830. }
  69831. // try splitting polygon into two and triangulate them independently
  69832. function splitEarcut(start, triangles, dim, minX, minY, size) {
  69833. // look for a valid diagonal that divides the polygon into two
  69834. var a = start;
  69835. do {
  69836. var b = a.next.next;
  69837. while (b !== a.prev) {
  69838. if (a.i !== b.i && isValidDiagonal(a, b)) {
  69839. // split the polygon in two by the diagonal
  69840. var c = splitPolygon(a, b);
  69841. // filter colinear points around the cuts
  69842. a = filterPoints(a, a.next);
  69843. c = filterPoints(c, c.next);
  69844. // run earcut on each half
  69845. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  69846. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  69847. return;
  69848. }
  69849. b = b.next;
  69850. }
  69851. a = a.next;
  69852. } while (a !== start);
  69853. }
  69854. // link every hole into the outer loop, producing a single-ring polygon without holes
  69855. function eliminateHoles(data, holeIndices, outerNode, dim) {
  69856. var queue = [], i, len, start, end, list;
  69857. for (i = 0, len = holeIndices.length; i < len; i++) {
  69858. start = holeIndices[i] * dim;
  69859. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69860. list = linkedList(data, start, end, dim, false);
  69861. if (list === list.next)
  69862. list.steiner = true;
  69863. queue.push(getLeftmost(list));
  69864. }
  69865. queue.sort(compareX);
  69866. // process holes from left to right
  69867. for (i = 0; i < queue.length; i++) {
  69868. eliminateHole(queue[i], outerNode);
  69869. outerNode = filterPoints(outerNode, outerNode.next);
  69870. }
  69871. return outerNode;
  69872. }
  69873. function compareX(a, b) {
  69874. return a.x - b.x;
  69875. }
  69876. // find a bridge between vertices that connects hole with an outer ring and and link it
  69877. function eliminateHole(hole, outerNode) {
  69878. outerNode = findHoleBridge(hole, outerNode);
  69879. if (outerNode) {
  69880. var b = splitPolygon(outerNode, hole);
  69881. filterPoints(b, b.next);
  69882. }
  69883. }
  69884. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  69885. function findHoleBridge(hole, outerNode) {
  69886. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  69887. // find a segment intersected by a ray from the hole's leftmost point to the left;
  69888. // segment's endpoint with lesser x will be potential connection point
  69889. do {
  69890. if (hy <= p.y && hy >= p.next.y) {
  69891. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  69892. if (x <= hx && x > qx) {
  69893. qx = x;
  69894. if (x === hx) {
  69895. if (hy === p.y)
  69896. return p;
  69897. if (hy === p.next.y)
  69898. return p.next;
  69899. }
  69900. m = p.x < p.next.x ? p : p.next;
  69901. }
  69902. }
  69903. p = p.next;
  69904. } while (p !== outerNode);
  69905. if (!m)
  69906. return null;
  69907. if (hx === qx)
  69908. return m.prev; // hole touches outer segment; pick lower endpoint
  69909. // look for points inside the triangle of hole point, segment intersection and endpoint;
  69910. // if there are no points found, we have a valid connection;
  69911. // otherwise choose the point of the minimum angle with the ray as connection point
  69912. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  69913. p = m.next;
  69914. while (p !== stop) {
  69915. if (hx >= p.x &&
  69916. p.x >= mx &&
  69917. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  69918. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  69919. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  69920. m = p;
  69921. tanMin = tan;
  69922. }
  69923. }
  69924. p = p.next;
  69925. }
  69926. return m;
  69927. }
  69928. // interlink polygon nodes in z-order
  69929. function indexCurve(start, minX, minY, size) {
  69930. var p = start;
  69931. do {
  69932. if (p.z === null)
  69933. p.z = zOrder(p.x, p.y, minX, minY, size);
  69934. p.prevZ = p.prev;
  69935. p.nextZ = p.next;
  69936. p = p.next;
  69937. } while (p !== start);
  69938. p.prevZ.nextZ = null;
  69939. p.prevZ = null;
  69940. sortLinked(p);
  69941. }
  69942. // Simon Tatham's linked list merge sort algorithm
  69943. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  69944. function sortLinked(list) {
  69945. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  69946. do {
  69947. p = list;
  69948. list = null;
  69949. tail = null;
  69950. numMerges = 0;
  69951. while (p) {
  69952. numMerges++;
  69953. q = p;
  69954. pSize = 0;
  69955. for (i = 0; i < inSize; i++) {
  69956. pSize++;
  69957. q = q.nextZ;
  69958. if (!q)
  69959. break;
  69960. }
  69961. qSize = inSize;
  69962. while (pSize > 0 || (qSize > 0 && q)) {
  69963. if (pSize === 0) {
  69964. e = q;
  69965. q = q.nextZ;
  69966. qSize--;
  69967. }
  69968. else if (qSize === 0 || !q) {
  69969. e = p;
  69970. p = p.nextZ;
  69971. pSize--;
  69972. }
  69973. else if (p.z <= q.z) {
  69974. e = p;
  69975. p = p.nextZ;
  69976. pSize--;
  69977. }
  69978. else {
  69979. e = q;
  69980. q = q.nextZ;
  69981. qSize--;
  69982. }
  69983. if (tail)
  69984. tail.nextZ = e;
  69985. else
  69986. list = e;
  69987. e.prevZ = tail;
  69988. tail = e;
  69989. }
  69990. p = q;
  69991. }
  69992. tail.nextZ = null;
  69993. inSize *= 2;
  69994. } while (numMerges > 1);
  69995. return list;
  69996. }
  69997. // z-order of a point given coords and size of the data bounding box
  69998. function zOrder(x, y, minX, minY, size) {
  69999. // coords are transformed into non-negative 15-bit integer range
  70000. x = 32767 * (x - minX) / size;
  70001. y = 32767 * (y - minY) / size;
  70002. x = (x | (x << 8)) & 0x00FF00FF;
  70003. x = (x | (x << 4)) & 0x0F0F0F0F;
  70004. x = (x | (x << 2)) & 0x33333333;
  70005. x = (x | (x << 1)) & 0x55555555;
  70006. y = (y | (y << 8)) & 0x00FF00FF;
  70007. y = (y | (y << 4)) & 0x0F0F0F0F;
  70008. y = (y | (y << 2)) & 0x33333333;
  70009. y = (y | (y << 1)) & 0x55555555;
  70010. return x | (y << 1);
  70011. }
  70012. // find the leftmost node of a polygon ring
  70013. function getLeftmost(start) {
  70014. var p = start, leftmost = start;
  70015. do {
  70016. if (p.x < leftmost.x)
  70017. leftmost = p;
  70018. p = p.next;
  70019. } while (p !== start);
  70020. return leftmost;
  70021. }
  70022. // check if a point lies within a convex triangle
  70023. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  70024. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  70025. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  70026. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  70027. }
  70028. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  70029. function isValidDiagonal(a, b) {
  70030. return a.next.i !== b.i &&
  70031. a.prev.i !== b.i &&
  70032. !intersectsPolygon(a, b) &&
  70033. locallyInside(a, b) &&
  70034. locallyInside(b, a) &&
  70035. middleInside(a, b);
  70036. }
  70037. // signed area of a triangle
  70038. function area(p, q, r) {
  70039. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  70040. }
  70041. // check if two points are equal
  70042. function equals(p1, p2) {
  70043. return p1.x === p2.x && p1.y === p2.y;
  70044. }
  70045. // check if two segments intersect
  70046. function intersects(p1, q1, p2, q2) {
  70047. if ((equals(p1, q1) && equals(p2, q2)) ||
  70048. (equals(p1, q2) && equals(p2, q1)))
  70049. return true;
  70050. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  70051. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  70052. }
  70053. // check if a polygon diagonal intersects any polygon segments
  70054. function intersectsPolygon(a, b) {
  70055. var p = a;
  70056. do {
  70057. if (p.i !== a.i &&
  70058. p.next.i !== a.i &&
  70059. p.i !== b.i &&
  70060. p.next.i !== b.i &&
  70061. intersects(p, p.next, a, b))
  70062. return true;
  70063. p = p.next;
  70064. } while (p !== a);
  70065. return false;
  70066. }
  70067. // check if a polygon diagonal is locally inside the polygon
  70068. function locallyInside(a, b) {
  70069. return area(a.prev, a, a.next) < 0
  70070. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  70071. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  70072. }
  70073. // check if the middle point of a polygon diagonal is inside the polygon
  70074. function middleInside(a, b) {
  70075. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  70076. do {
  70077. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  70078. inside = !inside;
  70079. p = p.next;
  70080. } while (p !== a);
  70081. return inside;
  70082. }
  70083. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  70084. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  70085. function splitPolygon(a, b) {
  70086. 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;
  70087. a.next = b;
  70088. b.prev = a;
  70089. a2.next = an;
  70090. an.prev = a2;
  70091. b2.next = a2;
  70092. a2.prev = b2;
  70093. bp.next = b2;
  70094. b2.prev = bp;
  70095. return b2;
  70096. }
  70097. // create a node and optionally link it with previous one (in a circular doubly linked list)
  70098. function insertNode(i, x, y, last) {
  70099. var p = new Node(i, x, y);
  70100. if (!last) {
  70101. p.prev = p;
  70102. p.next = p;
  70103. }
  70104. else {
  70105. p.next = last.next;
  70106. p.prev = last;
  70107. last.next.prev = p;
  70108. last.next = p;
  70109. }
  70110. return p;
  70111. }
  70112. function removeNode(p) {
  70113. p.next.prev = p.prev;
  70114. p.prev.next = p.next;
  70115. if (p.prevZ)
  70116. p.prevZ.nextZ = p.nextZ;
  70117. if (p.nextZ)
  70118. p.nextZ.prevZ = p.prevZ;
  70119. }
  70120. /**
  70121. * return a percentage difference between the polygon area and its triangulation area;
  70122. * used to verify correctness of triangulation
  70123. */
  70124. function deviation(data, holeIndices, dim, triangles) {
  70125. var hasHoles = holeIndices && holeIndices.length;
  70126. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  70127. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  70128. if (hasHoles) {
  70129. for (var i = 0, len = holeIndices.length; i < len; i++) {
  70130. var start = holeIndices[i] * dim;
  70131. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  70132. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  70133. }
  70134. }
  70135. var trianglesArea = 0;
  70136. for (i = 0; i < triangles.length; i += 3) {
  70137. var a = triangles[i] * dim;
  70138. var b = triangles[i + 1] * dim;
  70139. var c = triangles[i + 2] * dim;
  70140. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  70141. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  70142. }
  70143. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  70144. }
  70145. Earcut.deviation = deviation;
  70146. ;
  70147. function signedArea(data, start, end, dim) {
  70148. var sum = 0;
  70149. for (var i = start, j = end - dim; i < end; i += dim) {
  70150. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  70151. j = i;
  70152. }
  70153. return sum;
  70154. }
  70155. /**
  70156. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  70157. */
  70158. function flatten(data) {
  70159. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  70160. for (var i = 0; i < data.length; i++) {
  70161. for (var j = 0; j < data[i].length; j++) {
  70162. for (var d = 0; d < dim; d++)
  70163. result.vertices.push(data[i][j][d]);
  70164. }
  70165. if (i > 0) {
  70166. holeIndex += data[i - 1].length;
  70167. result.holes.push(holeIndex);
  70168. }
  70169. }
  70170. return result;
  70171. }
  70172. Earcut.flatten = flatten;
  70173. ;
  70174. })(Earcut || (Earcut = {}));
  70175. //# sourceMappingURL=babylon.earcut.js.map
  70176. var BABYLON;
  70177. (function (BABYLON) {
  70178. var IndexedVector2 = /** @class */ (function (_super) {
  70179. __extends(IndexedVector2, _super);
  70180. function IndexedVector2(original, index) {
  70181. var _this = _super.call(this, original.x, original.y) || this;
  70182. _this.index = index;
  70183. return _this;
  70184. }
  70185. return IndexedVector2;
  70186. }(BABYLON.Vector2));
  70187. var PolygonPoints = /** @class */ (function () {
  70188. function PolygonPoints() {
  70189. this.elements = new Array();
  70190. }
  70191. PolygonPoints.prototype.add = function (originalPoints) {
  70192. var _this = this;
  70193. var result = new Array();
  70194. originalPoints.forEach(function (point) {
  70195. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  70196. var newPoint = new IndexedVector2(point, _this.elements.length);
  70197. result.push(newPoint);
  70198. _this.elements.push(newPoint);
  70199. }
  70200. });
  70201. return result;
  70202. };
  70203. PolygonPoints.prototype.computeBounds = function () {
  70204. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70205. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70206. this.elements.forEach(function (point) {
  70207. // x
  70208. if (point.x < lmin.x) {
  70209. lmin.x = point.x;
  70210. }
  70211. else if (point.x > lmax.x) {
  70212. lmax.x = point.x;
  70213. }
  70214. // y
  70215. if (point.y < lmin.y) {
  70216. lmin.y = point.y;
  70217. }
  70218. else if (point.y > lmax.y) {
  70219. lmax.y = point.y;
  70220. }
  70221. });
  70222. return {
  70223. min: lmin,
  70224. max: lmax,
  70225. width: lmax.x - lmin.x,
  70226. height: lmax.y - lmin.y
  70227. };
  70228. };
  70229. return PolygonPoints;
  70230. }());
  70231. var Polygon = /** @class */ (function () {
  70232. function Polygon() {
  70233. }
  70234. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  70235. return [
  70236. new BABYLON.Vector2(xmin, ymin),
  70237. new BABYLON.Vector2(xmax, ymin),
  70238. new BABYLON.Vector2(xmax, ymax),
  70239. new BABYLON.Vector2(xmin, ymax)
  70240. ];
  70241. };
  70242. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  70243. if (cx === void 0) { cx = 0; }
  70244. if (cy === void 0) { cy = 0; }
  70245. if (numberOfSides === void 0) { numberOfSides = 32; }
  70246. var result = new Array();
  70247. var angle = 0;
  70248. var increment = (Math.PI * 2) / numberOfSides;
  70249. for (var i = 0; i < numberOfSides; i++) {
  70250. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  70251. angle -= increment;
  70252. }
  70253. return result;
  70254. };
  70255. Polygon.Parse = function (input) {
  70256. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  70257. var i, result = [];
  70258. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  70259. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  70260. }
  70261. return result;
  70262. };
  70263. Polygon.StartingAt = function (x, y) {
  70264. return BABYLON.Path2.StartingAt(x, y);
  70265. };
  70266. return Polygon;
  70267. }());
  70268. BABYLON.Polygon = Polygon;
  70269. var PolygonMeshBuilder = /** @class */ (function () {
  70270. function PolygonMeshBuilder(name, contours, scene) {
  70271. this._points = new PolygonPoints();
  70272. this._outlinepoints = new PolygonPoints();
  70273. this._holes = new Array();
  70274. this._epoints = new Array();
  70275. this._eholes = new Array();
  70276. this._name = name;
  70277. this._scene = scene;
  70278. var points;
  70279. if (contours instanceof BABYLON.Path2) {
  70280. points = contours.getPoints();
  70281. }
  70282. else {
  70283. points = contours;
  70284. }
  70285. this._addToepoint(points);
  70286. this._points.add(points);
  70287. this._outlinepoints.add(points);
  70288. }
  70289. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  70290. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  70291. var p = points_1[_i];
  70292. this._epoints.push(p.x, p.y);
  70293. }
  70294. };
  70295. PolygonMeshBuilder.prototype.addHole = function (hole) {
  70296. this._points.add(hole);
  70297. var holepoints = new PolygonPoints();
  70298. holepoints.add(hole);
  70299. this._holes.push(holepoints);
  70300. this._eholes.push(this._epoints.length / 2);
  70301. this._addToepoint(hole);
  70302. return this;
  70303. };
  70304. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  70305. var _this = this;
  70306. if (updatable === void 0) { updatable = false; }
  70307. if (depth === void 0) { depth = 0; }
  70308. var result = new BABYLON.Mesh(this._name, this._scene);
  70309. var normals = new Array();
  70310. var positions = new Array();
  70311. var uvs = new Array();
  70312. var bounds = this._points.computeBounds();
  70313. this._points.elements.forEach(function (p) {
  70314. normals.push(0, 1.0, 0);
  70315. positions.push(p.x, 0, p.y);
  70316. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  70317. });
  70318. var indices = new Array();
  70319. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  70320. for (var i = 0; i < res.length; i++) {
  70321. indices.push(res[i]);
  70322. }
  70323. if (depth > 0) {
  70324. var positionscount = (positions.length / 3); //get the current pointcount
  70325. this._points.elements.forEach(function (p) {
  70326. normals.push(0, -1.0, 0);
  70327. positions.push(p.x, -depth, p.y);
  70328. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  70329. });
  70330. var totalCount = indices.length;
  70331. for (var i = 0; i < totalCount; i += 3) {
  70332. var i0 = indices[i + 0];
  70333. var i1 = indices[i + 1];
  70334. var i2 = indices[i + 2];
  70335. indices.push(i2 + positionscount);
  70336. indices.push(i1 + positionscount);
  70337. indices.push(i0 + positionscount);
  70338. }
  70339. //Add the sides
  70340. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  70341. this._holes.forEach(function (hole) {
  70342. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  70343. });
  70344. }
  70345. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  70346. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  70347. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  70348. result.setIndices(indices);
  70349. return result;
  70350. };
  70351. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  70352. var StartIndex = positions.length / 3;
  70353. var ulength = 0;
  70354. for (var i = 0; i < points.elements.length; i++) {
  70355. var p = points.elements[i];
  70356. var p1;
  70357. if ((i + 1) > points.elements.length - 1) {
  70358. p1 = points.elements[0];
  70359. }
  70360. else {
  70361. p1 = points.elements[i + 1];
  70362. }
  70363. positions.push(p.x, 0, p.y);
  70364. positions.push(p.x, -depth, p.y);
  70365. positions.push(p1.x, 0, p1.y);
  70366. positions.push(p1.x, -depth, p1.y);
  70367. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  70368. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  70369. var v3 = v2.subtract(v1);
  70370. var v4 = new BABYLON.Vector3(0, 1, 0);
  70371. var vn = BABYLON.Vector3.Cross(v3, v4);
  70372. vn = vn.normalize();
  70373. uvs.push(ulength / bounds.width, 0);
  70374. uvs.push(ulength / bounds.width, 1);
  70375. ulength += v3.length();
  70376. uvs.push((ulength / bounds.width), 0);
  70377. uvs.push((ulength / bounds.width), 1);
  70378. if (!flip) {
  70379. normals.push(-vn.x, -vn.y, -vn.z);
  70380. normals.push(-vn.x, -vn.y, -vn.z);
  70381. normals.push(-vn.x, -vn.y, -vn.z);
  70382. normals.push(-vn.x, -vn.y, -vn.z);
  70383. indices.push(StartIndex);
  70384. indices.push(StartIndex + 1);
  70385. indices.push(StartIndex + 2);
  70386. indices.push(StartIndex + 1);
  70387. indices.push(StartIndex + 3);
  70388. indices.push(StartIndex + 2);
  70389. }
  70390. else {
  70391. normals.push(vn.x, vn.y, vn.z);
  70392. normals.push(vn.x, vn.y, vn.z);
  70393. normals.push(vn.x, vn.y, vn.z);
  70394. normals.push(vn.x, vn.y, vn.z);
  70395. indices.push(StartIndex);
  70396. indices.push(StartIndex + 2);
  70397. indices.push(StartIndex + 1);
  70398. indices.push(StartIndex + 1);
  70399. indices.push(StartIndex + 2);
  70400. indices.push(StartIndex + 3);
  70401. }
  70402. StartIndex += 4;
  70403. }
  70404. ;
  70405. };
  70406. return PolygonMeshBuilder;
  70407. }());
  70408. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  70409. })(BABYLON || (BABYLON = {}));
  70410. //# sourceMappingURL=babylon.polygonMesh.js.map
  70411. var BABYLON;
  70412. (function (BABYLON) {
  70413. // Unique ID when we import meshes from Babylon to CSG
  70414. var currentCSGMeshId = 0;
  70415. // # class Vertex
  70416. // Represents a vertex of a polygon. Use your own vertex class instead of this
  70417. // one to provide additional features like texture coordinates and vertex
  70418. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  70419. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  70420. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  70421. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  70422. // is not used anywhere else.
  70423. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  70424. var Vertex = /** @class */ (function () {
  70425. function Vertex(pos, normal, uv) {
  70426. this.pos = pos;
  70427. this.normal = normal;
  70428. this.uv = uv;
  70429. }
  70430. Vertex.prototype.clone = function () {
  70431. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  70432. };
  70433. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  70434. // orientation of a polygon is flipped.
  70435. Vertex.prototype.flip = function () {
  70436. this.normal = this.normal.scale(-1);
  70437. };
  70438. // Create a new vertex between this vertex and `other` by linearly
  70439. // interpolating all properties using a parameter of `t`. Subclasses should
  70440. // override this to interpolate additional properties.
  70441. Vertex.prototype.interpolate = function (other, t) {
  70442. 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));
  70443. };
  70444. return Vertex;
  70445. }());
  70446. // # class Plane
  70447. // Represents a plane in 3D space.
  70448. var Plane = /** @class */ (function () {
  70449. function Plane(normal, w) {
  70450. this.normal = normal;
  70451. this.w = w;
  70452. }
  70453. Plane.FromPoints = function (a, b, c) {
  70454. var v0 = c.subtract(a);
  70455. var v1 = b.subtract(a);
  70456. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70457. return null;
  70458. }
  70459. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70460. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70461. };
  70462. Plane.prototype.clone = function () {
  70463. return new Plane(this.normal.clone(), this.w);
  70464. };
  70465. Plane.prototype.flip = function () {
  70466. this.normal.scaleInPlace(-1);
  70467. this.w = -this.w;
  70468. };
  70469. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70470. // fragments in the appropriate lists. Coplanar polygons go into either
  70471. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70472. // respect to this plane. Polygons in front or in back of this plane go into
  70473. // either `front` or `back`.
  70474. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70475. var COPLANAR = 0;
  70476. var FRONT = 1;
  70477. var BACK = 2;
  70478. var SPANNING = 3;
  70479. // Classify each point as well as the entire polygon into one of the above
  70480. // four classes.
  70481. var polygonType = 0;
  70482. var types = [];
  70483. var i;
  70484. var t;
  70485. for (i = 0; i < polygon.vertices.length; i++) {
  70486. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70487. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70488. polygonType |= type;
  70489. types.push(type);
  70490. }
  70491. // Put the polygon in the correct list, splitting it when necessary.
  70492. switch (polygonType) {
  70493. case COPLANAR:
  70494. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70495. break;
  70496. case FRONT:
  70497. front.push(polygon);
  70498. break;
  70499. case BACK:
  70500. back.push(polygon);
  70501. break;
  70502. case SPANNING:
  70503. var f = [], b = [];
  70504. for (i = 0; i < polygon.vertices.length; i++) {
  70505. var j = (i + 1) % polygon.vertices.length;
  70506. var ti = types[i], tj = types[j];
  70507. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70508. if (ti !== BACK)
  70509. f.push(vi);
  70510. if (ti !== FRONT)
  70511. b.push(ti !== BACK ? vi.clone() : vi);
  70512. if ((ti | tj) === SPANNING) {
  70513. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70514. var v = vi.interpolate(vj, t);
  70515. f.push(v);
  70516. b.push(v.clone());
  70517. }
  70518. }
  70519. var poly;
  70520. if (f.length >= 3) {
  70521. poly = new Polygon(f, polygon.shared);
  70522. if (poly.plane)
  70523. front.push(poly);
  70524. }
  70525. if (b.length >= 3) {
  70526. poly = new Polygon(b, polygon.shared);
  70527. if (poly.plane)
  70528. back.push(poly);
  70529. }
  70530. break;
  70531. }
  70532. };
  70533. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70534. // point is on the plane.
  70535. Plane.EPSILON = 1e-5;
  70536. return Plane;
  70537. }());
  70538. // # class Polygon
  70539. // Represents a convex polygon. The vertices used to initialize a polygon must
  70540. // be coplanar and form a convex loop.
  70541. //
  70542. // Each convex polygon has a `shared` property, which is shared between all
  70543. // polygons that are clones of each other or were split from the same polygon.
  70544. // This can be used to define per-polygon properties (such as surface color).
  70545. var Polygon = /** @class */ (function () {
  70546. function Polygon(vertices, shared) {
  70547. this.vertices = vertices;
  70548. this.shared = shared;
  70549. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70550. }
  70551. Polygon.prototype.clone = function () {
  70552. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70553. return new Polygon(vertices, this.shared);
  70554. };
  70555. Polygon.prototype.flip = function () {
  70556. this.vertices.reverse().map(function (v) { v.flip(); });
  70557. this.plane.flip();
  70558. };
  70559. return Polygon;
  70560. }());
  70561. // # class Node
  70562. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70563. // by picking a polygon to split along. That polygon (and all other coplanar
  70564. // polygons) are added directly to that node and the other polygons are added to
  70565. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70566. // no distinction between internal and leaf nodes.
  70567. var Node = /** @class */ (function () {
  70568. function Node(polygons) {
  70569. this.plane = null;
  70570. this.front = null;
  70571. this.back = null;
  70572. this.polygons = new Array();
  70573. if (polygons) {
  70574. this.build(polygons);
  70575. }
  70576. }
  70577. Node.prototype.clone = function () {
  70578. var node = new Node();
  70579. node.plane = this.plane && this.plane.clone();
  70580. node.front = this.front && this.front.clone();
  70581. node.back = this.back && this.back.clone();
  70582. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70583. return node;
  70584. };
  70585. // Convert solid space to empty space and empty space to solid space.
  70586. Node.prototype.invert = function () {
  70587. for (var i = 0; i < this.polygons.length; i++) {
  70588. this.polygons[i].flip();
  70589. }
  70590. if (this.plane) {
  70591. this.plane.flip();
  70592. }
  70593. if (this.front) {
  70594. this.front.invert();
  70595. }
  70596. if (this.back) {
  70597. this.back.invert();
  70598. }
  70599. var temp = this.front;
  70600. this.front = this.back;
  70601. this.back = temp;
  70602. };
  70603. // Recursively remove all polygons in `polygons` that are inside this BSP
  70604. // tree.
  70605. Node.prototype.clipPolygons = function (polygons) {
  70606. if (!this.plane)
  70607. return polygons.slice();
  70608. var front = new Array(), back = new Array();
  70609. for (var i = 0; i < polygons.length; i++) {
  70610. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70611. }
  70612. if (this.front) {
  70613. front = this.front.clipPolygons(front);
  70614. }
  70615. if (this.back) {
  70616. back = this.back.clipPolygons(back);
  70617. }
  70618. else {
  70619. back = [];
  70620. }
  70621. return front.concat(back);
  70622. };
  70623. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70624. // `bsp`.
  70625. Node.prototype.clipTo = function (bsp) {
  70626. this.polygons = bsp.clipPolygons(this.polygons);
  70627. if (this.front)
  70628. this.front.clipTo(bsp);
  70629. if (this.back)
  70630. this.back.clipTo(bsp);
  70631. };
  70632. // Return a list of all polygons in this BSP tree.
  70633. Node.prototype.allPolygons = function () {
  70634. var polygons = this.polygons.slice();
  70635. if (this.front)
  70636. polygons = polygons.concat(this.front.allPolygons());
  70637. if (this.back)
  70638. polygons = polygons.concat(this.back.allPolygons());
  70639. return polygons;
  70640. };
  70641. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70642. // new polygons are filtered down to the bottom of the tree and become new
  70643. // nodes there. Each set of polygons is partitioned using the first polygon
  70644. // (no heuristic is used to pick a good split).
  70645. Node.prototype.build = function (polygons) {
  70646. if (!polygons.length)
  70647. return;
  70648. if (!this.plane)
  70649. this.plane = polygons[0].plane.clone();
  70650. var front = new Array(), back = new Array();
  70651. for (var i = 0; i < polygons.length; i++) {
  70652. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70653. }
  70654. if (front.length) {
  70655. if (!this.front)
  70656. this.front = new Node();
  70657. this.front.build(front);
  70658. }
  70659. if (back.length) {
  70660. if (!this.back)
  70661. this.back = new Node();
  70662. this.back.build(back);
  70663. }
  70664. };
  70665. return Node;
  70666. }());
  70667. var CSG = /** @class */ (function () {
  70668. function CSG() {
  70669. this.polygons = new Array();
  70670. }
  70671. // Convert BABYLON.Mesh to BABYLON.CSG
  70672. CSG.FromMesh = function (mesh) {
  70673. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70674. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70675. if (mesh instanceof BABYLON.Mesh) {
  70676. mesh.computeWorldMatrix(true);
  70677. matrix = mesh.getWorldMatrix();
  70678. meshPosition = mesh.position.clone();
  70679. meshRotation = mesh.rotation.clone();
  70680. if (mesh.rotationQuaternion) {
  70681. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70682. }
  70683. meshScaling = mesh.scaling.clone();
  70684. }
  70685. else {
  70686. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70687. }
  70688. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70689. var subMeshes = mesh.subMeshes;
  70690. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70691. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70692. vertices = [];
  70693. for (var j = 0; j < 3; j++) {
  70694. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70695. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70696. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70697. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70698. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70699. vertex = new Vertex(position, normal, uv);
  70700. vertices.push(vertex);
  70701. }
  70702. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70703. // To handle the case of degenerated triangle
  70704. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70705. if (polygon.plane)
  70706. polygons.push(polygon);
  70707. }
  70708. }
  70709. var csg = CSG.FromPolygons(polygons);
  70710. csg.matrix = matrix;
  70711. csg.position = meshPosition;
  70712. csg.rotation = meshRotation;
  70713. csg.scaling = meshScaling;
  70714. csg.rotationQuaternion = meshRotationQuaternion;
  70715. currentCSGMeshId++;
  70716. return csg;
  70717. };
  70718. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70719. CSG.FromPolygons = function (polygons) {
  70720. var csg = new CSG();
  70721. csg.polygons = polygons;
  70722. return csg;
  70723. };
  70724. CSG.prototype.clone = function () {
  70725. var csg = new CSG();
  70726. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70727. csg.copyTransformAttributes(this);
  70728. return csg;
  70729. };
  70730. CSG.prototype.union = function (csg) {
  70731. var a = new Node(this.clone().polygons);
  70732. var b = new Node(csg.clone().polygons);
  70733. a.clipTo(b);
  70734. b.clipTo(a);
  70735. b.invert();
  70736. b.clipTo(a);
  70737. b.invert();
  70738. a.build(b.allPolygons());
  70739. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70740. };
  70741. CSG.prototype.unionInPlace = function (csg) {
  70742. var a = new Node(this.polygons);
  70743. var b = new Node(csg.polygons);
  70744. a.clipTo(b);
  70745. b.clipTo(a);
  70746. b.invert();
  70747. b.clipTo(a);
  70748. b.invert();
  70749. a.build(b.allPolygons());
  70750. this.polygons = a.allPolygons();
  70751. };
  70752. CSG.prototype.subtract = function (csg) {
  70753. var a = new Node(this.clone().polygons);
  70754. var b = new Node(csg.clone().polygons);
  70755. a.invert();
  70756. a.clipTo(b);
  70757. b.clipTo(a);
  70758. b.invert();
  70759. b.clipTo(a);
  70760. b.invert();
  70761. a.build(b.allPolygons());
  70762. a.invert();
  70763. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70764. };
  70765. CSG.prototype.subtractInPlace = function (csg) {
  70766. var a = new Node(this.polygons);
  70767. var b = new Node(csg.polygons);
  70768. a.invert();
  70769. a.clipTo(b);
  70770. b.clipTo(a);
  70771. b.invert();
  70772. b.clipTo(a);
  70773. b.invert();
  70774. a.build(b.allPolygons());
  70775. a.invert();
  70776. this.polygons = a.allPolygons();
  70777. };
  70778. CSG.prototype.intersect = function (csg) {
  70779. var a = new Node(this.clone().polygons);
  70780. var b = new Node(csg.clone().polygons);
  70781. a.invert();
  70782. b.clipTo(a);
  70783. b.invert();
  70784. a.clipTo(b);
  70785. b.clipTo(a);
  70786. a.build(b.allPolygons());
  70787. a.invert();
  70788. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70789. };
  70790. CSG.prototype.intersectInPlace = function (csg) {
  70791. var a = new Node(this.polygons);
  70792. var b = new Node(csg.polygons);
  70793. a.invert();
  70794. b.clipTo(a);
  70795. b.invert();
  70796. a.clipTo(b);
  70797. b.clipTo(a);
  70798. a.build(b.allPolygons());
  70799. a.invert();
  70800. this.polygons = a.allPolygons();
  70801. };
  70802. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  70803. // not modified.
  70804. CSG.prototype.inverse = function () {
  70805. var csg = this.clone();
  70806. csg.inverseInPlace();
  70807. return csg;
  70808. };
  70809. CSG.prototype.inverseInPlace = function () {
  70810. this.polygons.map(function (p) { p.flip(); });
  70811. };
  70812. // This is used to keep meshes transformations so they can be restored
  70813. // when we build back a Babylon Mesh
  70814. // NB : All CSG operations are performed in world coordinates
  70815. CSG.prototype.copyTransformAttributes = function (csg) {
  70816. this.matrix = csg.matrix;
  70817. this.position = csg.position;
  70818. this.rotation = csg.rotation;
  70819. this.scaling = csg.scaling;
  70820. this.rotationQuaternion = csg.rotationQuaternion;
  70821. return this;
  70822. };
  70823. // Build Raw mesh from CSG
  70824. // Coordinates here are in world space
  70825. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  70826. var matrix = this.matrix.clone();
  70827. matrix.invert();
  70828. 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;
  70829. if (keepSubMeshes) {
  70830. // Sort Polygons, since subMeshes are indices range
  70831. polygons.sort(function (a, b) {
  70832. if (a.shared.meshId === b.shared.meshId) {
  70833. return a.shared.subMeshId - b.shared.subMeshId;
  70834. }
  70835. else {
  70836. return a.shared.meshId - b.shared.meshId;
  70837. }
  70838. });
  70839. }
  70840. for (var i = 0, il = polygons.length; i < il; i++) {
  70841. polygon = polygons[i];
  70842. // Building SubMeshes
  70843. if (!subMesh_dict[polygon.shared.meshId]) {
  70844. subMesh_dict[polygon.shared.meshId] = {};
  70845. }
  70846. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  70847. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  70848. indexStart: +Infinity,
  70849. indexEnd: -Infinity,
  70850. materialIndex: polygon.shared.materialIndex
  70851. };
  70852. }
  70853. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  70854. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  70855. polygonIndices[0] = 0;
  70856. polygonIndices[1] = j - 1;
  70857. polygonIndices[2] = j;
  70858. for (var k = 0; k < 3; k++) {
  70859. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  70860. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  70861. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  70862. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  70863. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  70864. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  70865. // Check if 2 points can be merged
  70866. if (!(typeof vertex_idx !== 'undefined' &&
  70867. normals[vertex_idx * 3] === localNormal.x &&
  70868. normals[vertex_idx * 3 + 1] === localNormal.y &&
  70869. normals[vertex_idx * 3 + 2] === localNormal.z &&
  70870. uvs[vertex_idx * 2] === uv.x &&
  70871. uvs[vertex_idx * 2 + 1] === uv.y)) {
  70872. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  70873. uvs.push(uv.x, uv.y);
  70874. normals.push(normal.x, normal.y, normal.z);
  70875. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  70876. }
  70877. indices.push(vertex_idx);
  70878. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  70879. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  70880. currentIndex++;
  70881. }
  70882. }
  70883. }
  70884. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  70885. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  70886. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  70887. mesh.setIndices(indices, null);
  70888. if (keepSubMeshes) {
  70889. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  70890. var materialIndexOffset = 0, materialMaxIndex;
  70891. mesh.subMeshes = new Array();
  70892. for (var m in subMesh_dict) {
  70893. materialMaxIndex = -1;
  70894. for (var sm in subMesh_dict[m]) {
  70895. subMesh_obj = subMesh_dict[m][sm];
  70896. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  70897. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  70898. }
  70899. materialIndexOffset += ++materialMaxIndex;
  70900. }
  70901. }
  70902. return mesh;
  70903. };
  70904. // Build Mesh from CSG taking material and transforms into account
  70905. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  70906. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  70907. mesh.material = material;
  70908. mesh.position.copyFrom(this.position);
  70909. mesh.rotation.copyFrom(this.rotation);
  70910. if (this.rotationQuaternion) {
  70911. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  70912. }
  70913. mesh.scaling.copyFrom(this.scaling);
  70914. mesh.computeWorldMatrix(true);
  70915. return mesh;
  70916. };
  70917. return CSG;
  70918. }());
  70919. BABYLON.CSG = CSG;
  70920. })(BABYLON || (BABYLON = {}));
  70921. //# sourceMappingURL=babylon.csg.js.map
  70922. var BABYLON;
  70923. (function (BABYLON) {
  70924. var LensFlare = /** @class */ (function () {
  70925. function LensFlare(size, position, color, imgUrl, system) {
  70926. this.size = size;
  70927. this.position = position;
  70928. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  70929. this.color = color || new BABYLON.Color3(1, 1, 1);
  70930. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  70931. this._system = system;
  70932. system.lensFlares.push(this);
  70933. }
  70934. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  70935. return new LensFlare(size, position, color, imgUrl, system);
  70936. };
  70937. LensFlare.prototype.dispose = function () {
  70938. if (this.texture) {
  70939. this.texture.dispose();
  70940. }
  70941. // Remove from scene
  70942. var index = this._system.lensFlares.indexOf(this);
  70943. this._system.lensFlares.splice(index, 1);
  70944. };
  70945. ;
  70946. return LensFlare;
  70947. }());
  70948. BABYLON.LensFlare = LensFlare;
  70949. })(BABYLON || (BABYLON = {}));
  70950. //# sourceMappingURL=babylon.lensFlare.js.map
  70951. var BABYLON;
  70952. (function (BABYLON) {
  70953. var LensFlareSystem = /** @class */ (function () {
  70954. function LensFlareSystem(name, emitter, scene) {
  70955. this.name = name;
  70956. this.lensFlares = new Array();
  70957. this.borderLimit = 300;
  70958. this.viewportBorder = 0;
  70959. this.layerMask = 0x0FFFFFFF;
  70960. this._vertexBuffers = {};
  70961. this._isEnabled = true;
  70962. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70963. this._emitter = emitter;
  70964. this.id = name;
  70965. scene.lensFlareSystems.push(this);
  70966. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  70967. var engine = scene.getEngine();
  70968. // VBO
  70969. var vertices = [];
  70970. vertices.push(1, 1);
  70971. vertices.push(-1, 1);
  70972. vertices.push(-1, -1);
  70973. vertices.push(1, -1);
  70974. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70975. // Indices
  70976. var indices = [];
  70977. indices.push(0);
  70978. indices.push(1);
  70979. indices.push(2);
  70980. indices.push(0);
  70981. indices.push(2);
  70982. indices.push(3);
  70983. this._indexBuffer = engine.createIndexBuffer(indices);
  70984. // Effects
  70985. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  70986. }
  70987. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  70988. get: function () {
  70989. return this._isEnabled;
  70990. },
  70991. set: function (value) {
  70992. this._isEnabled = value;
  70993. },
  70994. enumerable: true,
  70995. configurable: true
  70996. });
  70997. LensFlareSystem.prototype.getScene = function () {
  70998. return this._scene;
  70999. };
  71000. LensFlareSystem.prototype.getEmitter = function () {
  71001. return this._emitter;
  71002. };
  71003. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  71004. this._emitter = newEmitter;
  71005. };
  71006. LensFlareSystem.prototype.getEmitterPosition = function () {
  71007. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  71008. };
  71009. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  71010. var position = this.getEmitterPosition();
  71011. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  71012. this._positionX = position.x;
  71013. this._positionY = position.y;
  71014. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  71015. if (this.viewportBorder > 0) {
  71016. globalViewport.x -= this.viewportBorder;
  71017. globalViewport.y -= this.viewportBorder;
  71018. globalViewport.width += this.viewportBorder * 2;
  71019. globalViewport.height += this.viewportBorder * 2;
  71020. position.x += this.viewportBorder;
  71021. position.y += this.viewportBorder;
  71022. this._positionX += this.viewportBorder;
  71023. this._positionY += this.viewportBorder;
  71024. }
  71025. if (position.z > 0) {
  71026. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  71027. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  71028. return true;
  71029. }
  71030. return true;
  71031. }
  71032. return false;
  71033. };
  71034. LensFlareSystem.prototype._isVisible = function () {
  71035. if (!this._isEnabled || !this._scene.activeCamera) {
  71036. return false;
  71037. }
  71038. var emitterPosition = this.getEmitterPosition();
  71039. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  71040. var distance = direction.length();
  71041. direction.normalize();
  71042. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  71043. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  71044. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  71045. };
  71046. LensFlareSystem.prototype.render = function () {
  71047. if (!this._effect.isReady() || !this._scene.activeCamera)
  71048. return false;
  71049. var engine = this._scene.getEngine();
  71050. var viewport = this._scene.activeCamera.viewport;
  71051. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  71052. // Position
  71053. if (!this.computeEffectivePosition(globalViewport)) {
  71054. return false;
  71055. }
  71056. // Visibility
  71057. if (!this._isVisible()) {
  71058. return false;
  71059. }
  71060. // Intensity
  71061. var awayX;
  71062. var awayY;
  71063. if (this._positionX < this.borderLimit + globalViewport.x) {
  71064. awayX = this.borderLimit + globalViewport.x - this._positionX;
  71065. }
  71066. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  71067. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  71068. }
  71069. else {
  71070. awayX = 0;
  71071. }
  71072. if (this._positionY < this.borderLimit + globalViewport.y) {
  71073. awayY = this.borderLimit + globalViewport.y - this._positionY;
  71074. }
  71075. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  71076. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  71077. }
  71078. else {
  71079. awayY = 0;
  71080. }
  71081. var away = (awayX > awayY) ? awayX : awayY;
  71082. away -= this.viewportBorder;
  71083. if (away > this.borderLimit) {
  71084. away = this.borderLimit;
  71085. }
  71086. var intensity = 1.0 - (away / this.borderLimit);
  71087. if (intensity < 0) {
  71088. return false;
  71089. }
  71090. if (intensity > 1.0) {
  71091. intensity = 1.0;
  71092. }
  71093. if (this.viewportBorder > 0) {
  71094. globalViewport.x += this.viewportBorder;
  71095. globalViewport.y += this.viewportBorder;
  71096. globalViewport.width -= this.viewportBorder * 2;
  71097. globalViewport.height -= this.viewportBorder * 2;
  71098. this._positionX -= this.viewportBorder;
  71099. this._positionY -= this.viewportBorder;
  71100. }
  71101. // Position
  71102. var centerX = globalViewport.x + globalViewport.width / 2;
  71103. var centerY = globalViewport.y + globalViewport.height / 2;
  71104. var distX = centerX - this._positionX;
  71105. var distY = centerY - this._positionY;
  71106. // Effects
  71107. engine.enableEffect(this._effect);
  71108. engine.setState(false);
  71109. engine.setDepthBuffer(false);
  71110. // VBOs
  71111. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71112. // Flares
  71113. for (var index = 0; index < this.lensFlares.length; index++) {
  71114. var flare = this.lensFlares[index];
  71115. engine.setAlphaMode(flare.alphaMode);
  71116. var x = centerX - (distX * flare.position);
  71117. var y = centerY - (distY * flare.position);
  71118. var cw = flare.size;
  71119. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  71120. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  71121. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  71122. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  71123. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  71124. // Texture
  71125. this._effect.setTexture("textureSampler", flare.texture);
  71126. // Color
  71127. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  71128. // Draw order
  71129. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71130. }
  71131. engine.setDepthBuffer(true);
  71132. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71133. return true;
  71134. };
  71135. LensFlareSystem.prototype.dispose = function () {
  71136. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71137. if (vertexBuffer) {
  71138. vertexBuffer.dispose();
  71139. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71140. }
  71141. if (this._indexBuffer) {
  71142. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71143. this._indexBuffer = null;
  71144. }
  71145. while (this.lensFlares.length) {
  71146. this.lensFlares[0].dispose();
  71147. }
  71148. // Remove from scene
  71149. var index = this._scene.lensFlareSystems.indexOf(this);
  71150. this._scene.lensFlareSystems.splice(index, 1);
  71151. };
  71152. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  71153. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  71154. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  71155. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  71156. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  71157. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  71158. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  71159. var parsedFlare = parsedLensFlareSystem.flares[index];
  71160. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  71161. }
  71162. return lensFlareSystem;
  71163. };
  71164. LensFlareSystem.prototype.serialize = function () {
  71165. var serializationObject = {};
  71166. serializationObject.id = this.id;
  71167. serializationObject.name = this.name;
  71168. serializationObject.emitterId = this.getEmitter().id;
  71169. serializationObject.borderLimit = this.borderLimit;
  71170. serializationObject.flares = [];
  71171. for (var index = 0; index < this.lensFlares.length; index++) {
  71172. var flare = this.lensFlares[index];
  71173. serializationObject.flares.push({
  71174. size: flare.size,
  71175. position: flare.position,
  71176. color: flare.color.asArray(),
  71177. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  71178. });
  71179. }
  71180. return serializationObject;
  71181. };
  71182. return LensFlareSystem;
  71183. }());
  71184. BABYLON.LensFlareSystem = LensFlareSystem;
  71185. })(BABYLON || (BABYLON = {}));
  71186. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  71187. var BABYLON;
  71188. (function (BABYLON) {
  71189. /**
  71190. * This is a holder class for the physics joint created by the physics plugin.
  71191. * It holds a set of functions to control the underlying joint.
  71192. */
  71193. var PhysicsJoint = /** @class */ (function () {
  71194. function PhysicsJoint(type, jointData) {
  71195. this.type = type;
  71196. this.jointData = jointData;
  71197. jointData.nativeParams = jointData.nativeParams || {};
  71198. }
  71199. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  71200. get: function () {
  71201. return this._physicsJoint;
  71202. },
  71203. set: function (newJoint) {
  71204. if (this._physicsJoint) {
  71205. //remove from the wolrd
  71206. }
  71207. this._physicsJoint = newJoint;
  71208. },
  71209. enumerable: true,
  71210. configurable: true
  71211. });
  71212. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  71213. set: function (physicsPlugin) {
  71214. this._physicsPlugin = physicsPlugin;
  71215. },
  71216. enumerable: true,
  71217. configurable: true
  71218. });
  71219. /**
  71220. * Execute a function that is physics-plugin specific.
  71221. * @param {Function} func the function that will be executed.
  71222. * It accepts two parameters: the physics world and the physics joint.
  71223. */
  71224. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  71225. func(this._physicsPlugin.world, this._physicsJoint);
  71226. };
  71227. //TODO check if the native joints are the same
  71228. //Joint Types
  71229. PhysicsJoint.DistanceJoint = 0;
  71230. PhysicsJoint.HingeJoint = 1;
  71231. PhysicsJoint.BallAndSocketJoint = 2;
  71232. PhysicsJoint.WheelJoint = 3;
  71233. PhysicsJoint.SliderJoint = 4;
  71234. //OIMO
  71235. PhysicsJoint.PrismaticJoint = 5;
  71236. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  71237. PhysicsJoint.UniversalJoint = 6;
  71238. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  71239. //Cannon
  71240. //Similar to a Ball-Joint. Different in params
  71241. PhysicsJoint.PointToPointJoint = 8;
  71242. //Cannon only at the moment
  71243. PhysicsJoint.SpringJoint = 9;
  71244. PhysicsJoint.LockJoint = 10;
  71245. return PhysicsJoint;
  71246. }());
  71247. BABYLON.PhysicsJoint = PhysicsJoint;
  71248. /**
  71249. * A class representing a physics distance joint.
  71250. */
  71251. var DistanceJoint = /** @class */ (function (_super) {
  71252. __extends(DistanceJoint, _super);
  71253. function DistanceJoint(jointData) {
  71254. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  71255. }
  71256. /**
  71257. * Update the predefined distance.
  71258. */
  71259. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  71260. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  71261. };
  71262. return DistanceJoint;
  71263. }(PhysicsJoint));
  71264. BABYLON.DistanceJoint = DistanceJoint;
  71265. var MotorEnabledJoint = /** @class */ (function (_super) {
  71266. __extends(MotorEnabledJoint, _super);
  71267. function MotorEnabledJoint(type, jointData) {
  71268. return _super.call(this, type, jointData) || this;
  71269. }
  71270. /**
  71271. * Set the motor values.
  71272. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71273. * @param {number} force the force to apply
  71274. * @param {number} maxForce max force for this motor.
  71275. */
  71276. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  71277. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71278. };
  71279. /**
  71280. * Set the motor's limits.
  71281. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71282. */
  71283. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71284. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71285. };
  71286. return MotorEnabledJoint;
  71287. }(PhysicsJoint));
  71288. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  71289. /**
  71290. * This class represents a single hinge physics joint
  71291. */
  71292. var HingeJoint = /** @class */ (function (_super) {
  71293. __extends(HingeJoint, _super);
  71294. function HingeJoint(jointData) {
  71295. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  71296. }
  71297. /**
  71298. * Set the motor values.
  71299. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71300. * @param {number} force the force to apply
  71301. * @param {number} maxForce max force for this motor.
  71302. */
  71303. HingeJoint.prototype.setMotor = function (force, maxForce) {
  71304. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71305. };
  71306. /**
  71307. * Set the motor's limits.
  71308. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71309. */
  71310. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71311. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71312. };
  71313. return HingeJoint;
  71314. }(MotorEnabledJoint));
  71315. BABYLON.HingeJoint = HingeJoint;
  71316. /**
  71317. * This class represents a dual hinge physics joint (same as wheel joint)
  71318. */
  71319. var Hinge2Joint = /** @class */ (function (_super) {
  71320. __extends(Hinge2Joint, _super);
  71321. function Hinge2Joint(jointData) {
  71322. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  71323. }
  71324. /**
  71325. * Set the motor values.
  71326. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71327. * @param {number} force the force to apply
  71328. * @param {number} maxForce max force for this motor.
  71329. * @param {motorIndex} the motor's index, 0 or 1.
  71330. */
  71331. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  71332. if (motorIndex === void 0) { motorIndex = 0; }
  71333. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  71334. };
  71335. /**
  71336. * Set the motor limits.
  71337. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71338. * @param {number} upperLimit the upper limit
  71339. * @param {number} lowerLimit lower limit
  71340. * @param {motorIndex} the motor's index, 0 or 1.
  71341. */
  71342. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  71343. if (motorIndex === void 0) { motorIndex = 0; }
  71344. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  71345. };
  71346. return Hinge2Joint;
  71347. }(MotorEnabledJoint));
  71348. BABYLON.Hinge2Joint = Hinge2Joint;
  71349. })(BABYLON || (BABYLON = {}));
  71350. //# sourceMappingURL=babylon.physicsJoint.js.map
  71351. var BABYLON;
  71352. (function (BABYLON) {
  71353. var PhysicsImpostor = /** @class */ (function () {
  71354. function PhysicsImpostor(object, type, _options, _scene) {
  71355. if (_options === void 0) { _options = { mass: 0 }; }
  71356. var _this = this;
  71357. this.object = object;
  71358. this.type = type;
  71359. this._options = _options;
  71360. this._scene = _scene;
  71361. this._bodyUpdateRequired = false;
  71362. this._onBeforePhysicsStepCallbacks = new Array();
  71363. this._onAfterPhysicsStepCallbacks = new Array();
  71364. this._onPhysicsCollideCallbacks = [];
  71365. this._deltaPosition = BABYLON.Vector3.Zero();
  71366. this._isDisposed = false;
  71367. //temp variables for parent rotation calculations
  71368. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  71369. this._tmpQuat = new BABYLON.Quaternion();
  71370. this._tmpQuat2 = new BABYLON.Quaternion();
  71371. /**
  71372. * this function is executed by the physics engine.
  71373. */
  71374. this.beforeStep = function () {
  71375. if (!_this._physicsEngine) {
  71376. return;
  71377. }
  71378. _this.object.translate(_this._deltaPosition, -1);
  71379. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  71380. _this.object.computeWorldMatrix(false);
  71381. if (_this.object.parent && _this.object.rotationQuaternion) {
  71382. _this.getParentsRotation();
  71383. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  71384. }
  71385. else {
  71386. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  71387. }
  71388. if (!_this._options.disableBidirectionalTransformation) {
  71389. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  71390. }
  71391. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  71392. func(_this);
  71393. });
  71394. };
  71395. /**
  71396. * this function is executed by the physics engine.
  71397. */
  71398. this.afterStep = function () {
  71399. if (!_this._physicsEngine) {
  71400. return;
  71401. }
  71402. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  71403. func(_this);
  71404. });
  71405. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  71406. // object has now its world rotation. needs to be converted to local.
  71407. if (_this.object.parent && _this.object.rotationQuaternion) {
  71408. _this.getParentsRotation();
  71409. _this._tmpQuat.conjugateInPlace();
  71410. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  71411. }
  71412. // take the position set and make it the absolute position of this object.
  71413. _this.object.setAbsolutePosition(_this.object.position);
  71414. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  71415. _this.object.translate(_this._deltaPosition, 1);
  71416. };
  71417. /**
  71418. * Legacy collision detection event support
  71419. */
  71420. this.onCollideEvent = null;
  71421. //event and body object due to cannon's event-based architecture.
  71422. this.onCollide = function (e) {
  71423. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  71424. return;
  71425. }
  71426. if (!_this._physicsEngine) {
  71427. return;
  71428. }
  71429. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  71430. if (otherImpostor) {
  71431. // Legacy collision detection event support
  71432. if (_this.onCollideEvent) {
  71433. _this.onCollideEvent(_this, otherImpostor);
  71434. }
  71435. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  71436. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  71437. }).forEach(function (obj) {
  71438. obj.callback(_this, otherImpostor);
  71439. });
  71440. }
  71441. };
  71442. //sanity check!
  71443. if (!this.object) {
  71444. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  71445. return;
  71446. }
  71447. //legacy support for old syntax.
  71448. if (!this._scene && object.getScene) {
  71449. this._scene = object.getScene();
  71450. }
  71451. if (!this._scene) {
  71452. return;
  71453. }
  71454. this._physicsEngine = this._scene.getPhysicsEngine();
  71455. if (!this._physicsEngine) {
  71456. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71457. }
  71458. else {
  71459. //set the object's quaternion, if not set
  71460. if (!this.object.rotationQuaternion) {
  71461. if (this.object.rotation) {
  71462. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71463. }
  71464. else {
  71465. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71466. }
  71467. }
  71468. //default options params
  71469. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71470. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71471. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71472. this._joints = [];
  71473. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71474. if (!this.object.parent || this._options.ignoreParent) {
  71475. this._init();
  71476. }
  71477. else if (this.object.parent.physicsImpostor) {
  71478. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71479. }
  71480. }
  71481. }
  71482. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71483. get: function () {
  71484. return this._isDisposed;
  71485. },
  71486. enumerable: true,
  71487. configurable: true
  71488. });
  71489. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71490. get: function () {
  71491. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71492. },
  71493. set: function (value) {
  71494. this.setMass(value);
  71495. },
  71496. enumerable: true,
  71497. configurable: true
  71498. });
  71499. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71500. get: function () {
  71501. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71502. },
  71503. set: function (value) {
  71504. if (!this._physicsEngine) {
  71505. return;
  71506. }
  71507. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71508. },
  71509. enumerable: true,
  71510. configurable: true
  71511. });
  71512. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71513. get: function () {
  71514. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71515. },
  71516. set: function (value) {
  71517. if (!this._physicsEngine) {
  71518. return;
  71519. }
  71520. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71521. },
  71522. enumerable: true,
  71523. configurable: true
  71524. });
  71525. /**
  71526. * This function will completly initialize this impostor.
  71527. * It will create a new body - but only if this mesh has no parent.
  71528. * If it has, this impostor will not be used other than to define the impostor
  71529. * of the child mesh.
  71530. */
  71531. PhysicsImpostor.prototype._init = function () {
  71532. if (!this._physicsEngine) {
  71533. return;
  71534. }
  71535. this._physicsEngine.removeImpostor(this);
  71536. this.physicsBody = null;
  71537. this._parent = this._parent || this._getPhysicsParent();
  71538. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71539. this._physicsEngine.addImpostor(this);
  71540. }
  71541. };
  71542. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71543. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71544. var parentMesh = this.object.parent;
  71545. return parentMesh.physicsImpostor;
  71546. }
  71547. return null;
  71548. };
  71549. /**
  71550. * Should a new body be generated.
  71551. */
  71552. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71553. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71554. };
  71555. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71556. this.forceUpdate();
  71557. };
  71558. /**
  71559. * Force a regeneration of this or the parent's impostor's body.
  71560. * Use under cautious - This will remove all joints already implemented.
  71561. */
  71562. PhysicsImpostor.prototype.forceUpdate = function () {
  71563. this._init();
  71564. if (this.parent && !this._options.ignoreParent) {
  71565. this.parent.forceUpdate();
  71566. }
  71567. };
  71568. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71569. /*public get mesh(): AbstractMesh {
  71570. return this._mesh;
  71571. }*/
  71572. /**
  71573. * Gets the body that holds this impostor. Either its own, or its parent.
  71574. */
  71575. get: function () {
  71576. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71577. },
  71578. /**
  71579. * Set the physics body. Used mainly by the physics engine/plugin
  71580. */
  71581. set: function (physicsBody) {
  71582. if (this._physicsBody && this._physicsEngine) {
  71583. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71584. }
  71585. this._physicsBody = physicsBody;
  71586. this.resetUpdateFlags();
  71587. },
  71588. enumerable: true,
  71589. configurable: true
  71590. });
  71591. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71592. get: function () {
  71593. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71594. },
  71595. set: function (value) {
  71596. this._parent = value;
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71602. this._bodyUpdateRequired = false;
  71603. };
  71604. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71605. if (this.object.getBoundingInfo) {
  71606. var q = this.object.rotationQuaternion;
  71607. //reset rotation
  71608. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71609. //calculate the world matrix with no rotation
  71610. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71611. var boundingInfo = this.object.getBoundingInfo();
  71612. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71613. //bring back the rotation
  71614. this.object.rotationQuaternion = q;
  71615. //calculate the world matrix with the new rotation
  71616. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71617. return size;
  71618. }
  71619. else {
  71620. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71621. }
  71622. };
  71623. PhysicsImpostor.prototype.getObjectCenter = function () {
  71624. if (this.object.getBoundingInfo) {
  71625. var boundingInfo = this.object.getBoundingInfo();
  71626. return boundingInfo.boundingBox.centerWorld;
  71627. }
  71628. else {
  71629. return this.object.position;
  71630. }
  71631. };
  71632. /**
  71633. * Get a specific parametes from the options parameter.
  71634. */
  71635. PhysicsImpostor.prototype.getParam = function (paramName) {
  71636. return this._options[paramName];
  71637. };
  71638. /**
  71639. * Sets a specific parameter in the options given to the physics plugin
  71640. */
  71641. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71642. this._options[paramName] = value;
  71643. this._bodyUpdateRequired = true;
  71644. };
  71645. /**
  71646. * Specifically change the body's mass option. Won't recreate the physics body object
  71647. */
  71648. PhysicsImpostor.prototype.setMass = function (mass) {
  71649. if (this.getParam("mass") !== mass) {
  71650. this.setParam("mass", mass);
  71651. }
  71652. if (this._physicsEngine) {
  71653. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71654. }
  71655. };
  71656. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71657. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71658. };
  71659. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71660. if (this._physicsEngine) {
  71661. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71662. }
  71663. };
  71664. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71665. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71666. };
  71667. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71668. if (this._physicsEngine) {
  71669. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71670. }
  71671. };
  71672. /**
  71673. * Execute a function with the physics plugin native code.
  71674. * Provide a function the will have two variables - the world object and the physics body object.
  71675. */
  71676. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71677. if (this._physicsEngine) {
  71678. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71679. }
  71680. };
  71681. /**
  71682. * Register a function that will be executed before the physics world is stepping forward.
  71683. */
  71684. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71685. this._onBeforePhysicsStepCallbacks.push(func);
  71686. };
  71687. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71688. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71689. if (index > -1) {
  71690. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71691. }
  71692. else {
  71693. BABYLON.Tools.Warn("Function to remove was not found");
  71694. }
  71695. };
  71696. /**
  71697. * Register a function that will be executed after the physics step
  71698. */
  71699. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71700. this._onAfterPhysicsStepCallbacks.push(func);
  71701. };
  71702. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71703. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71704. if (index > -1) {
  71705. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71706. }
  71707. else {
  71708. BABYLON.Tools.Warn("Function to remove was not found");
  71709. }
  71710. };
  71711. /**
  71712. * register a function that will be executed when this impostor collides against a different body.
  71713. */
  71714. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71715. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71716. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71717. };
  71718. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71719. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71720. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71721. if (index > -1) {
  71722. this._onPhysicsCollideCallbacks.splice(index, 1);
  71723. }
  71724. else {
  71725. BABYLON.Tools.Warn("Function to remove was not found");
  71726. }
  71727. };
  71728. PhysicsImpostor.prototype.getParentsRotation = function () {
  71729. var parent = this.object.parent;
  71730. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71731. while (parent) {
  71732. if (parent.rotationQuaternion) {
  71733. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71734. }
  71735. else {
  71736. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71737. }
  71738. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71739. parent = parent.parent;
  71740. }
  71741. return this._tmpQuat;
  71742. };
  71743. /**
  71744. * Apply a force
  71745. */
  71746. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71747. if (this._physicsEngine) {
  71748. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71749. }
  71750. return this;
  71751. };
  71752. /**
  71753. * Apply an impulse
  71754. */
  71755. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71756. if (this._physicsEngine) {
  71757. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71758. }
  71759. return this;
  71760. };
  71761. /**
  71762. * A help function to create a joint.
  71763. */
  71764. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  71765. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  71766. this.addJoint(otherImpostor, joint);
  71767. return this;
  71768. };
  71769. /**
  71770. * Add a joint to this impostor with a different impostor.
  71771. */
  71772. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  71773. this._joints.push({
  71774. otherImpostor: otherImpostor,
  71775. joint: joint
  71776. });
  71777. if (this._physicsEngine) {
  71778. this._physicsEngine.addJoint(this, otherImpostor, joint);
  71779. }
  71780. return this;
  71781. };
  71782. /**
  71783. * Will keep this body still, in a sleep mode.
  71784. */
  71785. PhysicsImpostor.prototype.sleep = function () {
  71786. if (this._physicsEngine) {
  71787. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  71788. }
  71789. return this;
  71790. };
  71791. /**
  71792. * Wake the body up.
  71793. */
  71794. PhysicsImpostor.prototype.wakeUp = function () {
  71795. if (this._physicsEngine) {
  71796. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  71797. }
  71798. return this;
  71799. };
  71800. PhysicsImpostor.prototype.clone = function (newObject) {
  71801. if (!newObject)
  71802. return null;
  71803. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  71804. };
  71805. PhysicsImpostor.prototype.dispose = function () {
  71806. var _this = this;
  71807. //no dispose if no physics engine is available.
  71808. if (!this._physicsEngine) {
  71809. return;
  71810. }
  71811. this._joints.forEach(function (j) {
  71812. if (_this._physicsEngine) {
  71813. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  71814. }
  71815. });
  71816. //dispose the physics body
  71817. this._physicsEngine.removeImpostor(this);
  71818. if (this.parent) {
  71819. this.parent.forceUpdate();
  71820. }
  71821. else {
  71822. /*this._object.getChildMeshes().forEach(function(mesh) {
  71823. if (mesh.physicsImpostor) {
  71824. if (disposeChildren) {
  71825. mesh.physicsImpostor.dispose();
  71826. mesh.physicsImpostor = null;
  71827. }
  71828. }
  71829. })*/
  71830. }
  71831. this._isDisposed = true;
  71832. };
  71833. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  71834. this._deltaPosition.copyFrom(position);
  71835. };
  71836. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  71837. if (!this._deltaRotation) {
  71838. this._deltaRotation = new BABYLON.Quaternion();
  71839. }
  71840. this._deltaRotation.copyFrom(rotation);
  71841. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  71842. };
  71843. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  71844. if (this._physicsEngine) {
  71845. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  71846. }
  71847. return this;
  71848. };
  71849. PhysicsImpostor.prototype.getRadius = function () {
  71850. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  71851. };
  71852. /**
  71853. * Sync a bone with this impostor
  71854. * @param bone The bone to sync to the impostor.
  71855. * @param boneMesh The mesh that the bone is influencing.
  71856. * @param jointPivot The pivot of the joint / bone in local space.
  71857. * @param distToJoint Optional distance from the impostor to the joint.
  71858. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71859. */
  71860. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  71861. var tempVec = PhysicsImpostor._tmpVecs[0];
  71862. var mesh = this.object;
  71863. if (mesh.rotationQuaternion) {
  71864. if (adjustRotation) {
  71865. var tempQuat = PhysicsImpostor._tmpQuat;
  71866. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  71867. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  71868. }
  71869. else {
  71870. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  71871. }
  71872. }
  71873. tempVec.x = 0;
  71874. tempVec.y = 0;
  71875. tempVec.z = 0;
  71876. if (jointPivot) {
  71877. tempVec.x = jointPivot.x;
  71878. tempVec.y = jointPivot.y;
  71879. tempVec.z = jointPivot.z;
  71880. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  71881. if (distToJoint === undefined || distToJoint === null) {
  71882. distToJoint = jointPivot.length();
  71883. }
  71884. tempVec.x *= distToJoint;
  71885. tempVec.y *= distToJoint;
  71886. tempVec.z *= distToJoint;
  71887. }
  71888. if (bone.getParent()) {
  71889. tempVec.addInPlace(mesh.getAbsolutePosition());
  71890. bone.setAbsolutePosition(tempVec, boneMesh);
  71891. }
  71892. else {
  71893. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  71894. boneMesh.position.x -= tempVec.x;
  71895. boneMesh.position.y -= tempVec.y;
  71896. boneMesh.position.z -= tempVec.z;
  71897. }
  71898. };
  71899. /**
  71900. * Sync impostor to a bone
  71901. * @param bone The bone that the impostor will be synced to.
  71902. * @param boneMesh The mesh that the bone is influencing.
  71903. * @param jointPivot The pivot of the joint / bone in local space.
  71904. * @param distToJoint Optional distance from the impostor to the joint.
  71905. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71906. * @param boneAxis Optional vector3 axis the bone is aligned with
  71907. */
  71908. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  71909. var mesh = this.object;
  71910. if (mesh.rotationQuaternion) {
  71911. if (adjustRotation) {
  71912. var tempQuat = PhysicsImpostor._tmpQuat;
  71913. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  71914. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  71915. }
  71916. else {
  71917. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  71918. }
  71919. }
  71920. var pos = PhysicsImpostor._tmpVecs[0];
  71921. var boneDir = PhysicsImpostor._tmpVecs[1];
  71922. if (!boneAxis) {
  71923. boneAxis = PhysicsImpostor._tmpVecs[2];
  71924. boneAxis.x = 0;
  71925. boneAxis.y = 1;
  71926. boneAxis.z = 0;
  71927. }
  71928. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  71929. bone.getAbsolutePositionToRef(boneMesh, pos);
  71930. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  71931. distToJoint = jointPivot.length();
  71932. }
  71933. if (distToJoint !== undefined && distToJoint !== null) {
  71934. pos.x += boneDir.x * distToJoint;
  71935. pos.y += boneDir.y * distToJoint;
  71936. pos.z += boneDir.z * distToJoint;
  71937. }
  71938. mesh.setAbsolutePosition(pos);
  71939. };
  71940. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  71941. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  71942. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71943. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  71944. //Impostor types
  71945. PhysicsImpostor.NoImpostor = 0;
  71946. PhysicsImpostor.SphereImpostor = 1;
  71947. PhysicsImpostor.BoxImpostor = 2;
  71948. PhysicsImpostor.PlaneImpostor = 3;
  71949. PhysicsImpostor.MeshImpostor = 4;
  71950. PhysicsImpostor.CylinderImpostor = 7;
  71951. PhysicsImpostor.ParticleImpostor = 8;
  71952. PhysicsImpostor.HeightmapImpostor = 9;
  71953. return PhysicsImpostor;
  71954. }());
  71955. BABYLON.PhysicsImpostor = PhysicsImpostor;
  71956. })(BABYLON || (BABYLON = {}));
  71957. //# sourceMappingURL=babylon.physicsImpostor.js.map
  71958. var BABYLON;
  71959. (function (BABYLON) {
  71960. var PhysicsEngine = /** @class */ (function () {
  71961. function PhysicsEngine(gravity, _physicsPlugin) {
  71962. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  71963. this._physicsPlugin = _physicsPlugin;
  71964. //new methods and parameters
  71965. this._impostors = [];
  71966. this._joints = [];
  71967. if (!this._physicsPlugin.isSupported()) {
  71968. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  71969. + "Please make sure it is included.");
  71970. }
  71971. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  71972. this.setGravity(gravity);
  71973. this.setTimeStep();
  71974. }
  71975. PhysicsEngine.prototype.setGravity = function (gravity) {
  71976. this.gravity = gravity;
  71977. this._physicsPlugin.setGravity(this.gravity);
  71978. };
  71979. /**
  71980. * Set the time step of the physics engine.
  71981. * default is 1/60.
  71982. * To slow it down, enter 1/600 for example.
  71983. * To speed it up, 1/30
  71984. * @param {number} newTimeStep the new timestep to apply to this world.
  71985. */
  71986. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  71987. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  71988. this._physicsPlugin.setTimeStep(newTimeStep);
  71989. };
  71990. /**
  71991. * Get the time step of the physics engine.
  71992. */
  71993. PhysicsEngine.prototype.getTimeStep = function () {
  71994. return this._physicsPlugin.getTimeStep();
  71995. };
  71996. PhysicsEngine.prototype.dispose = function () {
  71997. this._impostors.forEach(function (impostor) {
  71998. impostor.dispose();
  71999. });
  72000. this._physicsPlugin.dispose();
  72001. };
  72002. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  72003. return this._physicsPlugin.name;
  72004. };
  72005. /**
  72006. * Adding a new impostor for the impostor tracking.
  72007. * This will be done by the impostor itself.
  72008. * @param {PhysicsImpostor} impostor the impostor to add
  72009. */
  72010. PhysicsEngine.prototype.addImpostor = function (impostor) {
  72011. impostor.uniqueId = this._impostors.push(impostor);
  72012. //if no parent, generate the body
  72013. if (!impostor.parent) {
  72014. this._physicsPlugin.generatePhysicsBody(impostor);
  72015. }
  72016. };
  72017. /**
  72018. * Remove an impostor from the engine.
  72019. * This impostor and its mesh will not longer be updated by the physics engine.
  72020. * @param {PhysicsImpostor} impostor the impostor to remove
  72021. */
  72022. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  72023. var index = this._impostors.indexOf(impostor);
  72024. if (index > -1) {
  72025. var removed = this._impostors.splice(index, 1);
  72026. //Is it needed?
  72027. if (removed.length) {
  72028. //this will also remove it from the world.
  72029. removed[0].physicsBody = null;
  72030. }
  72031. }
  72032. };
  72033. /**
  72034. * Add a joint to the physics engine
  72035. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  72036. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  72037. * @param {PhysicsJoint} the joint that will connect both impostors.
  72038. */
  72039. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  72040. var impostorJoint = {
  72041. mainImpostor: mainImpostor,
  72042. connectedImpostor: connectedImpostor,
  72043. joint: joint
  72044. };
  72045. joint.physicsPlugin = this._physicsPlugin;
  72046. this._joints.push(impostorJoint);
  72047. this._physicsPlugin.generateJoint(impostorJoint);
  72048. };
  72049. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  72050. var matchingJoints = this._joints.filter(function (impostorJoint) {
  72051. return (impostorJoint.connectedImpostor === connectedImpostor
  72052. && impostorJoint.joint === joint
  72053. && impostorJoint.mainImpostor === mainImpostor);
  72054. });
  72055. if (matchingJoints.length) {
  72056. this._physicsPlugin.removeJoint(matchingJoints[0]);
  72057. //TODO remove it from the list as well
  72058. }
  72059. };
  72060. /**
  72061. * Called by the scene. no need to call it.
  72062. */
  72063. PhysicsEngine.prototype._step = function (delta) {
  72064. var _this = this;
  72065. //check if any mesh has no body / requires an update
  72066. this._impostors.forEach(function (impostor) {
  72067. if (impostor.isBodyInitRequired()) {
  72068. _this._physicsPlugin.generatePhysicsBody(impostor);
  72069. }
  72070. });
  72071. if (delta > 0.1) {
  72072. delta = 0.1;
  72073. }
  72074. else if (delta <= 0) {
  72075. delta = 1.0 / 60.0;
  72076. }
  72077. this._physicsPlugin.executeStep(delta, this._impostors);
  72078. };
  72079. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  72080. return this._physicsPlugin;
  72081. };
  72082. PhysicsEngine.prototype.getImpostors = function () {
  72083. return this._impostors;
  72084. };
  72085. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  72086. for (var i = 0; i < this._impostors.length; ++i) {
  72087. if (this._impostors[i].object === object) {
  72088. return this._impostors[i];
  72089. }
  72090. }
  72091. return null;
  72092. };
  72093. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  72094. for (var i = 0; i < this._impostors.length; ++i) {
  72095. if (this._impostors[i].physicsBody === body) {
  72096. return this._impostors[i];
  72097. }
  72098. }
  72099. return null;
  72100. };
  72101. // Statics
  72102. PhysicsEngine.Epsilon = 0.001;
  72103. return PhysicsEngine;
  72104. }());
  72105. BABYLON.PhysicsEngine = PhysicsEngine;
  72106. })(BABYLON || (BABYLON = {}));
  72107. //# sourceMappingURL=babylon.physicsEngine.js.map
  72108. var BABYLON;
  72109. (function (BABYLON) {
  72110. var PhysicsHelper = /** @class */ (function () {
  72111. function PhysicsHelper(scene) {
  72112. this._scene = scene;
  72113. this._physicsEngine = this._scene.getPhysicsEngine();
  72114. if (!this._physicsEngine) {
  72115. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  72116. }
  72117. }
  72118. /**
  72119. * @param {Vector3} origin the origin of the explosion
  72120. * @param {number} radius the explosion radius
  72121. * @param {number} strength the explosion strength
  72122. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72123. */
  72124. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  72125. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72126. if (!this._physicsEngine) {
  72127. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  72128. return null;
  72129. }
  72130. var impostors = this._physicsEngine.getImpostors();
  72131. if (impostors.length === 0) {
  72132. return null;
  72133. }
  72134. var event = new PhysicsRadialExplosionEvent(this._scene);
  72135. impostors.forEach(function (impostor) {
  72136. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  72137. if (!impostorForceAndContactPoint) {
  72138. return;
  72139. }
  72140. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72141. });
  72142. event.dispose(false);
  72143. return event;
  72144. };
  72145. /**
  72146. * @param {Vector3} origin the origin of the explosion
  72147. * @param {number} radius the explosion radius
  72148. * @param {number} strength the explosion strength
  72149. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72150. */
  72151. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  72152. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72153. if (!this._physicsEngine) {
  72154. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72155. return null;
  72156. }
  72157. var impostors = this._physicsEngine.getImpostors();
  72158. if (impostors.length === 0) {
  72159. return null;
  72160. }
  72161. var event = new PhysicsRadialExplosionEvent(this._scene);
  72162. impostors.forEach(function (impostor) {
  72163. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  72164. if (!impostorForceAndContactPoint) {
  72165. return;
  72166. }
  72167. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72168. });
  72169. event.dispose(false);
  72170. return event;
  72171. };
  72172. /**
  72173. * @param {Vector3} origin the origin of the explosion
  72174. * @param {number} radius the explosion radius
  72175. * @param {number} strength the explosion strength
  72176. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72177. */
  72178. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  72179. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72180. if (!this._physicsEngine) {
  72181. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72182. return null;
  72183. }
  72184. var impostors = this._physicsEngine.getImpostors();
  72185. if (impostors.length === 0) {
  72186. return null;
  72187. }
  72188. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  72189. event.dispose(false);
  72190. return event;
  72191. };
  72192. /**
  72193. * @param {Vector3} origin the origin of the updraft
  72194. * @param {number} radius the radius of the updraft
  72195. * @param {number} strength the strength of the updraft
  72196. * @param {number} height the height of the updraft
  72197. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  72198. */
  72199. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  72200. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  72201. if (!this._physicsEngine) {
  72202. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72203. return null;
  72204. }
  72205. if (this._physicsEngine.getImpostors().length === 0) {
  72206. return null;
  72207. }
  72208. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  72209. event.dispose(false);
  72210. return event;
  72211. };
  72212. /**
  72213. * @param {Vector3} origin the of the vortex
  72214. * @param {number} radius the radius of the vortex
  72215. * @param {number} strength the strength of the vortex
  72216. * @param {number} height the height of the vortex
  72217. */
  72218. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  72219. if (!this._physicsEngine) {
  72220. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72221. return null;
  72222. }
  72223. if (this._physicsEngine.getImpostors().length === 0) {
  72224. return null;
  72225. }
  72226. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  72227. event.dispose(false);
  72228. return event;
  72229. };
  72230. return PhysicsHelper;
  72231. }());
  72232. BABYLON.PhysicsHelper = PhysicsHelper;
  72233. /***** Radial explosion *****/
  72234. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  72235. function PhysicsRadialExplosionEvent(scene) {
  72236. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  72237. this._rays = [];
  72238. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  72239. this._scene = scene;
  72240. }
  72241. /**
  72242. * Returns the data related to the radial explosion event (sphere & rays).
  72243. * @returns {PhysicsRadialExplosionEventData}
  72244. */
  72245. PhysicsRadialExplosionEvent.prototype.getData = function () {
  72246. this._dataFetched = true;
  72247. return {
  72248. sphere: this._sphere,
  72249. rays: this._rays,
  72250. };
  72251. };
  72252. /**
  72253. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  72254. * @param impostor
  72255. * @param {Vector3} origin the origin of the explosion
  72256. * @param {number} radius the explosion radius
  72257. * @param {number} strength the explosion strength
  72258. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  72259. * @returns {Nullable<PhysicsForceAndContactPoint>}
  72260. */
  72261. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  72262. if (impostor.mass === 0) {
  72263. return null;
  72264. }
  72265. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  72266. return null;
  72267. }
  72268. if (impostor.object.getClassName() !== 'Mesh') {
  72269. return null;
  72270. }
  72271. var impostorObject = impostor.object;
  72272. var impostorObjectCenter = impostor.getObjectCenter();
  72273. var direction = impostorObjectCenter.subtract(origin);
  72274. var ray = new BABYLON.Ray(origin, direction, radius);
  72275. this._rays.push(ray);
  72276. var hit = ray.intersectsMesh(impostorObject);
  72277. var contactPoint = hit.pickedPoint;
  72278. if (!contactPoint) {
  72279. return null;
  72280. }
  72281. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  72282. if (distanceFromOrigin > radius) {
  72283. return null;
  72284. }
  72285. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  72286. ? strength
  72287. : strength * (1 - (distanceFromOrigin / radius));
  72288. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72289. return { force: force, contactPoint: contactPoint };
  72290. };
  72291. /**
  72292. * Disposes the sphere.
  72293. * @param {bolean} force
  72294. */
  72295. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  72296. var _this = this;
  72297. if (force === void 0) { force = true; }
  72298. if (force) {
  72299. this._sphere.dispose();
  72300. }
  72301. else {
  72302. setTimeout(function () {
  72303. if (!_this._dataFetched) {
  72304. _this._sphere.dispose();
  72305. }
  72306. }, 0);
  72307. }
  72308. };
  72309. /*** Helpers ***/
  72310. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  72311. if (!this._sphere) {
  72312. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  72313. this._sphere.isVisible = false;
  72314. }
  72315. };
  72316. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  72317. var impostorObject = impostor.object;
  72318. this._prepareSphere();
  72319. this._sphere.position = origin;
  72320. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  72321. this._sphere._updateBoundingInfo();
  72322. this._sphere.computeWorldMatrix(true);
  72323. return this._sphere.intersectsMesh(impostorObject, true);
  72324. };
  72325. return PhysicsRadialExplosionEvent;
  72326. }());
  72327. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  72328. /***** Gravitational Field *****/
  72329. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  72330. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  72331. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72332. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72333. this._physicsHelper = physicsHelper;
  72334. this._scene = scene;
  72335. this._origin = origin;
  72336. this._radius = radius;
  72337. this._strength = strength;
  72338. this._falloff = falloff;
  72339. this._tickCallback = this._tick.bind(this);
  72340. }
  72341. /**
  72342. * Returns the data related to the gravitational field event (sphere).
  72343. * @returns {PhysicsGravitationalFieldEventData}
  72344. */
  72345. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  72346. this._dataFetched = true;
  72347. return {
  72348. sphere: this._sphere,
  72349. };
  72350. };
  72351. /**
  72352. * Enables the gravitational field.
  72353. */
  72354. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  72355. this._tickCallback.call(this);
  72356. this._scene.registerBeforeRender(this._tickCallback);
  72357. };
  72358. /**
  72359. * Disables the gravitational field.
  72360. */
  72361. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  72362. this._scene.unregisterBeforeRender(this._tickCallback);
  72363. };
  72364. /**
  72365. * Disposes the sphere.
  72366. * @param {bolean} force
  72367. */
  72368. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  72369. var _this = this;
  72370. if (force === void 0) { force = true; }
  72371. if (force) {
  72372. this._sphere.dispose();
  72373. }
  72374. else {
  72375. setTimeout(function () {
  72376. if (!_this._dataFetched) {
  72377. _this._sphere.dispose();
  72378. }
  72379. }, 0);
  72380. }
  72381. };
  72382. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  72383. // Since the params won't change, we fetch the event only once
  72384. if (this._sphere) {
  72385. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72386. }
  72387. else {
  72388. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72389. if (radialExplosionEvent) {
  72390. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  72391. }
  72392. }
  72393. };
  72394. return PhysicsGravitationalFieldEvent;
  72395. }());
  72396. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  72397. /***** Updraft *****/
  72398. var PhysicsUpdraftEvent = /** @class */ (function () {
  72399. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  72400. this._scene = _scene;
  72401. this._origin = _origin;
  72402. this._radius = _radius;
  72403. this._strength = _strength;
  72404. this._height = _height;
  72405. this._updraftMode = _updraftMode;
  72406. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72407. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  72408. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72409. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72410. this._physicsEngine = this._scene.getPhysicsEngine();
  72411. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72412. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72413. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72414. this._originDirection = this._origin.subtract(this._originTop).normalize();
  72415. }
  72416. this._tickCallback = this._tick.bind(this);
  72417. }
  72418. /**
  72419. * Returns the data related to the updraft event (cylinder).
  72420. * @returns {PhysicsUpdraftEventData}
  72421. */
  72422. PhysicsUpdraftEvent.prototype.getData = function () {
  72423. this._dataFetched = true;
  72424. return {
  72425. cylinder: this._cylinder,
  72426. };
  72427. };
  72428. /**
  72429. * Enables the updraft.
  72430. */
  72431. PhysicsUpdraftEvent.prototype.enable = function () {
  72432. this._tickCallback.call(this);
  72433. this._scene.registerBeforeRender(this._tickCallback);
  72434. };
  72435. /**
  72436. * Disables the cortex.
  72437. */
  72438. PhysicsUpdraftEvent.prototype.disable = function () {
  72439. this._scene.unregisterBeforeRender(this._tickCallback);
  72440. };
  72441. /**
  72442. * Disposes the sphere.
  72443. * @param {bolean} force
  72444. */
  72445. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  72446. var _this = this;
  72447. if (force === void 0) { force = true; }
  72448. if (force) {
  72449. this._cylinder.dispose();
  72450. }
  72451. else {
  72452. setTimeout(function () {
  72453. if (!_this._dataFetched) {
  72454. _this._cylinder.dispose();
  72455. }
  72456. }, 0);
  72457. }
  72458. };
  72459. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72460. if (impostor.mass === 0) {
  72461. return null;
  72462. }
  72463. if (!this._intersectsWithCylinder(impostor)) {
  72464. return null;
  72465. }
  72466. var impostorObjectCenter = impostor.getObjectCenter();
  72467. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72468. var direction = this._originDirection;
  72469. }
  72470. else {
  72471. var direction = impostorObjectCenter.subtract(this._originTop);
  72472. }
  72473. var multiplier = this._strength * -1;
  72474. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72475. return { force: force, contactPoint: impostorObjectCenter };
  72476. };
  72477. PhysicsUpdraftEvent.prototype._tick = function () {
  72478. var _this = this;
  72479. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72480. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72481. if (!impostorForceAndContactPoint) {
  72482. return;
  72483. }
  72484. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72485. });
  72486. };
  72487. /*** Helpers ***/
  72488. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72489. if (!this._cylinder) {
  72490. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72491. height: this._height,
  72492. diameter: this._radius * 2,
  72493. }, this._scene);
  72494. this._cylinder.isVisible = false;
  72495. }
  72496. };
  72497. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72498. var impostorObject = impostor.object;
  72499. this._prepareCylinder();
  72500. this._cylinder.position = this._cylinderPosition;
  72501. return this._cylinder.intersectsMesh(impostorObject, true);
  72502. };
  72503. return PhysicsUpdraftEvent;
  72504. }());
  72505. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72506. /***** Vortex *****/
  72507. var PhysicsVortexEvent = /** @class */ (function () {
  72508. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72509. this._scene = _scene;
  72510. this._origin = _origin;
  72511. this._radius = _radius;
  72512. this._strength = _strength;
  72513. this._height = _height;
  72514. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72515. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72516. this._updraftMultiplier = 0.02;
  72517. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72518. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72519. this._physicsEngine = this._scene.getPhysicsEngine();
  72520. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72521. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72522. this._tickCallback = this._tick.bind(this);
  72523. }
  72524. /**
  72525. * Returns the data related to the vortex event (cylinder).
  72526. * @returns {PhysicsVortexEventData}
  72527. */
  72528. PhysicsVortexEvent.prototype.getData = function () {
  72529. this._dataFetched = true;
  72530. return {
  72531. cylinder: this._cylinder,
  72532. };
  72533. };
  72534. /**
  72535. * Enables the vortex.
  72536. */
  72537. PhysicsVortexEvent.prototype.enable = function () {
  72538. this._tickCallback.call(this);
  72539. this._scene.registerBeforeRender(this._tickCallback);
  72540. };
  72541. /**
  72542. * Disables the cortex.
  72543. */
  72544. PhysicsVortexEvent.prototype.disable = function () {
  72545. this._scene.unregisterBeforeRender(this._tickCallback);
  72546. };
  72547. /**
  72548. * Disposes the sphere.
  72549. * @param {bolean} force
  72550. */
  72551. PhysicsVortexEvent.prototype.dispose = function (force) {
  72552. var _this = this;
  72553. if (force === void 0) { force = true; }
  72554. if (force) {
  72555. this._cylinder.dispose();
  72556. }
  72557. else {
  72558. setTimeout(function () {
  72559. if (!_this._dataFetched) {
  72560. _this._cylinder.dispose();
  72561. }
  72562. }, 0);
  72563. }
  72564. };
  72565. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72566. if (impostor.mass === 0) {
  72567. return null;
  72568. }
  72569. if (!this._intersectsWithCylinder(impostor)) {
  72570. return null;
  72571. }
  72572. if (impostor.object.getClassName() !== 'Mesh') {
  72573. return null;
  72574. }
  72575. var impostorObject = impostor.object;
  72576. var impostorObjectCenter = impostor.getObjectCenter();
  72577. 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)
  72578. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72579. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72580. var hit = ray.intersectsMesh(impostorObject);
  72581. var contactPoint = hit.pickedPoint;
  72582. if (!contactPoint) {
  72583. return null;
  72584. }
  72585. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72586. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72587. var directionToOrigin = contactPoint.normalize();
  72588. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72589. directionToOrigin = directionToOrigin.negate();
  72590. }
  72591. // TODO: find a more physically based solution
  72592. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72593. var forceX = directionToOrigin.x * this._strength / 8;
  72594. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72595. var forceZ = directionToOrigin.z * this._strength / 8;
  72596. }
  72597. else {
  72598. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72599. var forceY = this._originTop.y * this._updraftMultiplier;
  72600. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72601. }
  72602. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72603. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72604. return { force: force, contactPoint: impostorObjectCenter };
  72605. };
  72606. PhysicsVortexEvent.prototype._tick = function () {
  72607. var _this = this;
  72608. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72609. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72610. if (!impostorForceAndContactPoint) {
  72611. return;
  72612. }
  72613. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72614. });
  72615. };
  72616. /*** Helpers ***/
  72617. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72618. if (!this._cylinder) {
  72619. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72620. height: this._height,
  72621. diameter: this._radius * 2,
  72622. }, this._scene);
  72623. this._cylinder.isVisible = false;
  72624. }
  72625. };
  72626. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72627. var impostorObject = impostor.object;
  72628. this._prepareCylinder();
  72629. this._cylinder.position = this._cylinderPosition;
  72630. return this._cylinder.intersectsMesh(impostorObject, true);
  72631. };
  72632. return PhysicsVortexEvent;
  72633. }());
  72634. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72635. /***** Enums *****/
  72636. /**
  72637. * The strenght of the force in correspondence to the distance of the affected object
  72638. */
  72639. var PhysicsRadialImpulseFalloff;
  72640. (function (PhysicsRadialImpulseFalloff) {
  72641. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72642. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72643. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72644. /**
  72645. * The strenght of the force in correspondence to the distance of the affected object
  72646. */
  72647. var PhysicsUpdraftMode;
  72648. (function (PhysicsUpdraftMode) {
  72649. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72650. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72651. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72652. })(BABYLON || (BABYLON = {}));
  72653. //# sourceMappingURL=babylon.physicsHelper.js.map
  72654. var BABYLON;
  72655. (function (BABYLON) {
  72656. var CannonJSPlugin = /** @class */ (function () {
  72657. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72658. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72659. if (iterations === void 0) { iterations = 10; }
  72660. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72661. this.name = "CannonJSPlugin";
  72662. this._physicsMaterials = new Array();
  72663. this._fixedTimeStep = 1 / 60;
  72664. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72665. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72666. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72667. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72668. this._tmpPosition = BABYLON.Vector3.Zero();
  72669. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72670. this._tmpUnityRotation = new BABYLON.Quaternion();
  72671. if (!this.isSupported()) {
  72672. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72673. return;
  72674. }
  72675. this._extendNamespace();
  72676. this.world = new this.BJSCANNON.World();
  72677. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72678. this.world.solver.iterations = iterations;
  72679. }
  72680. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72681. this.world.gravity.copy(gravity);
  72682. };
  72683. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72684. this._fixedTimeStep = timeStep;
  72685. };
  72686. CannonJSPlugin.prototype.getTimeStep = function () {
  72687. return this._fixedTimeStep;
  72688. };
  72689. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72690. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72691. };
  72692. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72693. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72694. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72695. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72696. };
  72697. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72698. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72699. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72700. impostor.physicsBody.applyForce(impulse, worldPoint);
  72701. };
  72702. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72703. //parent-child relationship. Does this impostor has a parent impostor?
  72704. if (impostor.parent) {
  72705. if (impostor.physicsBody) {
  72706. this.removePhysicsBody(impostor);
  72707. //TODO is that needed?
  72708. impostor.forceUpdate();
  72709. }
  72710. return;
  72711. }
  72712. //should a new body be created for this impostor?
  72713. if (impostor.isBodyInitRequired()) {
  72714. var shape = this._createShape(impostor);
  72715. //unregister events, if body is being changed
  72716. var oldBody = impostor.physicsBody;
  72717. if (oldBody) {
  72718. this.removePhysicsBody(impostor);
  72719. }
  72720. //create the body and material
  72721. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72722. var bodyCreationObject = {
  72723. mass: impostor.getParam("mass"),
  72724. material: material
  72725. };
  72726. // A simple extend, in case native options were used.
  72727. var nativeOptions = impostor.getParam("nativeOptions");
  72728. for (var key in nativeOptions) {
  72729. if (nativeOptions.hasOwnProperty(key)) {
  72730. bodyCreationObject[key] = nativeOptions[key];
  72731. }
  72732. }
  72733. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72734. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72735. this.world.addEventListener("preStep", impostor.beforeStep);
  72736. this.world.addEventListener("postStep", impostor.afterStep);
  72737. impostor.physicsBody.addShape(shape);
  72738. this.world.add(impostor.physicsBody);
  72739. //try to keep the body moving in the right direction by taking old properties.
  72740. //Should be tested!
  72741. if (oldBody) {
  72742. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72743. impostor.physicsBody[param].copy(oldBody[param]);
  72744. });
  72745. }
  72746. this._processChildMeshes(impostor);
  72747. }
  72748. //now update the body's transformation
  72749. this._updatePhysicsBodyTransformation(impostor);
  72750. };
  72751. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72752. var _this = this;
  72753. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72754. var currentRotation = mainImpostor.object.rotationQuaternion;
  72755. if (meshChildren.length) {
  72756. var processMesh = function (localPosition, mesh) {
  72757. if (!currentRotation || !mesh.rotationQuaternion) {
  72758. return;
  72759. }
  72760. var childImpostor = mesh.getPhysicsImpostor();
  72761. if (childImpostor) {
  72762. var parent = childImpostor.parent;
  72763. if (parent !== mainImpostor) {
  72764. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  72765. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  72766. if (childImpostor.physicsBody) {
  72767. _this.removePhysicsBody(childImpostor);
  72768. childImpostor.physicsBody = null;
  72769. }
  72770. childImpostor.parent = mainImpostor;
  72771. childImpostor.resetUpdateFlags();
  72772. 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));
  72773. //Add the mass of the children.
  72774. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  72775. }
  72776. }
  72777. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  72778. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  72779. };
  72780. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  72781. }
  72782. };
  72783. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72784. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  72785. this.world.removeEventListener("preStep", impostor.beforeStep);
  72786. this.world.removeEventListener("postStep", impostor.afterStep);
  72787. this.world.remove(impostor.physicsBody);
  72788. };
  72789. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72790. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72791. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72792. if (!mainBody || !connectedBody) {
  72793. return;
  72794. }
  72795. var constraint;
  72796. var jointData = impostorJoint.joint.jointData;
  72797. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  72798. var constraintData = {
  72799. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  72800. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  72801. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  72802. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  72803. maxForce: jointData.nativeParams.maxForce,
  72804. collideConnected: !!jointData.collision
  72805. };
  72806. switch (impostorJoint.joint.type) {
  72807. case BABYLON.PhysicsJoint.HingeJoint:
  72808. case BABYLON.PhysicsJoint.Hinge2Joint:
  72809. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  72810. break;
  72811. case BABYLON.PhysicsJoint.DistanceJoint:
  72812. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  72813. break;
  72814. case BABYLON.PhysicsJoint.SpringJoint:
  72815. var springData = jointData;
  72816. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  72817. restLength: springData.length,
  72818. stiffness: springData.stiffness,
  72819. damping: springData.damping,
  72820. localAnchorA: constraintData.pivotA,
  72821. localAnchorB: constraintData.pivotB
  72822. });
  72823. break;
  72824. case BABYLON.PhysicsJoint.LockJoint:
  72825. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  72826. break;
  72827. case BABYLON.PhysicsJoint.PointToPointJoint:
  72828. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72829. default:
  72830. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  72831. break;
  72832. }
  72833. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  72834. constraint.collideConnected = !!jointData.collision;
  72835. impostorJoint.joint.physicsJoint = constraint;
  72836. //don't add spring as constraint, as it is not one.
  72837. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  72838. this.world.addConstraint(constraint);
  72839. }
  72840. else {
  72841. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  72842. constraint.applyForce();
  72843. });
  72844. }
  72845. };
  72846. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72847. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  72848. };
  72849. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  72850. var index;
  72851. var mat;
  72852. for (index = 0; index < this._physicsMaterials.length; index++) {
  72853. mat = this._physicsMaterials[index];
  72854. if (mat.friction === friction && mat.restitution === restitution) {
  72855. return mat;
  72856. }
  72857. }
  72858. var currentMat = new this.BJSCANNON.Material(name);
  72859. currentMat.friction = friction;
  72860. currentMat.restitution = restitution;
  72861. this._physicsMaterials.push(currentMat);
  72862. return currentMat;
  72863. };
  72864. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  72865. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  72866. };
  72867. CannonJSPlugin.prototype._createShape = function (impostor) {
  72868. var object = impostor.object;
  72869. var returnValue;
  72870. var extendSize = impostor.getObjectExtendSize();
  72871. switch (impostor.type) {
  72872. case BABYLON.PhysicsImpostor.SphereImpostor:
  72873. var radiusX = extendSize.x;
  72874. var radiusY = extendSize.y;
  72875. var radiusZ = extendSize.z;
  72876. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  72877. break;
  72878. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  72879. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72880. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  72881. break;
  72882. case BABYLON.PhysicsImpostor.BoxImpostor:
  72883. var box = extendSize.scale(0.5);
  72884. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  72885. break;
  72886. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72887. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  72888. returnValue = new this.BJSCANNON.Plane();
  72889. break;
  72890. case BABYLON.PhysicsImpostor.MeshImpostor:
  72891. // should transform the vertex data to world coordinates!!
  72892. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  72893. var rawFaces = object.getIndices ? object.getIndices() : [];
  72894. if (!rawVerts)
  72895. return;
  72896. // get only scale! so the object could transform correctly.
  72897. var oldPosition = object.position.clone();
  72898. var oldRotation = object.rotation && object.rotation.clone();
  72899. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  72900. object.position.copyFromFloats(0, 0, 0);
  72901. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72902. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72903. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72904. var transform = object.computeWorldMatrix(true);
  72905. // convert rawVerts to object space
  72906. var temp = new Array();
  72907. var index;
  72908. for (index = 0; index < rawVerts.length; index += 3) {
  72909. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  72910. }
  72911. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  72912. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  72913. //now set back the transformation!
  72914. object.position.copyFrom(oldPosition);
  72915. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  72916. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  72917. break;
  72918. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  72919. var oldPosition2 = object.position.clone();
  72920. var oldRotation2 = object.rotation && object.rotation.clone();
  72921. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  72922. object.position.copyFromFloats(0, 0, 0);
  72923. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72924. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72925. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72926. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  72927. returnValue = this._createHeightmap(object);
  72928. object.position.copyFrom(oldPosition2);
  72929. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  72930. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  72931. object.computeWorldMatrix(true);
  72932. break;
  72933. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72934. returnValue = new this.BJSCANNON.Particle();
  72935. break;
  72936. }
  72937. return returnValue;
  72938. };
  72939. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  72940. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  72941. var transform = object.computeWorldMatrix(true);
  72942. // convert rawVerts to object space
  72943. var temp = new Array();
  72944. var index;
  72945. for (index = 0; index < pos.length; index += 3) {
  72946. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  72947. }
  72948. pos = temp;
  72949. var matrix = new Array();
  72950. //For now pointDepth will not be used and will be automatically calculated.
  72951. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  72952. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  72953. var boundingInfo = object.getBoundingInfo();
  72954. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  72955. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  72956. var elementSize = dim * 2 / arraySize;
  72957. for (var i = 0; i < pos.length; i = i + 3) {
  72958. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  72959. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  72960. var y = -pos[i + 2] + minY;
  72961. if (!matrix[x]) {
  72962. matrix[x] = [];
  72963. }
  72964. if (!matrix[x][z]) {
  72965. matrix[x][z] = y;
  72966. }
  72967. matrix[x][z] = Math.max(y, matrix[x][z]);
  72968. }
  72969. for (var x = 0; x <= arraySize; ++x) {
  72970. if (!matrix[x]) {
  72971. var loc = 1;
  72972. while (!matrix[(x + loc) % arraySize]) {
  72973. loc++;
  72974. }
  72975. matrix[x] = matrix[(x + loc) % arraySize].slice();
  72976. //console.log("missing x", x);
  72977. }
  72978. for (var z = 0; z <= arraySize; ++z) {
  72979. if (!matrix[x][z]) {
  72980. var loc = 1;
  72981. var newValue;
  72982. while (newValue === undefined) {
  72983. newValue = matrix[x][(z + loc++) % arraySize];
  72984. }
  72985. matrix[x][z] = newValue;
  72986. }
  72987. }
  72988. }
  72989. var shape = new this.BJSCANNON.Heightfield(matrix, {
  72990. elementSize: elementSize
  72991. });
  72992. //For future reference, needed for body transformation
  72993. shape.minY = minY;
  72994. return shape;
  72995. };
  72996. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  72997. var object = impostor.object;
  72998. //make sure it is updated...
  72999. object.computeWorldMatrix && object.computeWorldMatrix(true);
  73000. // The delta between the mesh position and the mesh bounding box center
  73001. var bInfo = object.getBoundingInfo();
  73002. if (!bInfo)
  73003. return;
  73004. var center = impostor.getObjectCenter();
  73005. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  73006. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  73007. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  73008. this._tmpPosition.copyFrom(center);
  73009. var quaternion = object.rotationQuaternion;
  73010. if (!quaternion) {
  73011. return;
  73012. }
  73013. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  73014. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  73015. //-90 DEG in X, precalculated
  73016. quaternion = quaternion.multiply(this._minus90X);
  73017. //Invert! (Precalculated, 90 deg in X)
  73018. //No need to clone. this will never change.
  73019. impostor.setDeltaRotation(this._plus90X);
  73020. }
  73021. //If it is a heightfield, if should be centered.
  73022. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  73023. var mesh = object;
  73024. var boundingInfo = mesh.getBoundingInfo();
  73025. //calculate the correct body position:
  73026. var rotationQuaternion = mesh.rotationQuaternion;
  73027. mesh.rotationQuaternion = this._tmpUnityRotation;
  73028. mesh.computeWorldMatrix(true);
  73029. //get original center with no rotation
  73030. var c = center.clone();
  73031. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  73032. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  73033. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  73034. mesh.setPivotMatrix(p);
  73035. mesh.computeWorldMatrix(true);
  73036. //calculate the translation
  73037. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  73038. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  73039. //add it inverted to the delta
  73040. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  73041. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  73042. //rotation is back
  73043. mesh.rotationQuaternion = rotationQuaternion;
  73044. mesh.setPivotMatrix(oldPivot);
  73045. mesh.computeWorldMatrix(true);
  73046. }
  73047. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  73048. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  73049. //this._tmpPosition.copyFrom(object.position);
  73050. }
  73051. impostor.setDeltaPosition(this._tmpDeltaPosition);
  73052. //Now update the impostor object
  73053. impostor.physicsBody.position.copy(this._tmpPosition);
  73054. impostor.physicsBody.quaternion.copy(quaternion);
  73055. };
  73056. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73057. impostor.object.position.copyFrom(impostor.physicsBody.position);
  73058. if (impostor.object.rotationQuaternion) {
  73059. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  73060. }
  73061. };
  73062. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73063. impostor.physicsBody.position.copy(newPosition);
  73064. impostor.physicsBody.quaternion.copy(newRotation);
  73065. };
  73066. CannonJSPlugin.prototype.isSupported = function () {
  73067. return this.BJSCANNON !== undefined;
  73068. };
  73069. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73070. impostor.physicsBody.velocity.copy(velocity);
  73071. };
  73072. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73073. impostor.physicsBody.angularVelocity.copy(velocity);
  73074. };
  73075. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73076. var v = impostor.physicsBody.velocity;
  73077. if (!v) {
  73078. return null;
  73079. }
  73080. return new BABYLON.Vector3(v.x, v.y, v.z);
  73081. };
  73082. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73083. var v = impostor.physicsBody.angularVelocity;
  73084. if (!v) {
  73085. return null;
  73086. }
  73087. return new BABYLON.Vector3(v.x, v.y, v.z);
  73088. };
  73089. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73090. impostor.physicsBody.mass = mass;
  73091. impostor.physicsBody.updateMassProperties();
  73092. };
  73093. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  73094. return impostor.physicsBody.mass;
  73095. };
  73096. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  73097. return impostor.physicsBody.material.friction;
  73098. };
  73099. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73100. impostor.physicsBody.material.friction = friction;
  73101. };
  73102. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73103. return impostor.physicsBody.material.restitution;
  73104. };
  73105. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73106. impostor.physicsBody.material.restitution = restitution;
  73107. };
  73108. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  73109. impostor.physicsBody.sleep();
  73110. };
  73111. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  73112. impostor.physicsBody.wakeUp();
  73113. };
  73114. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73115. joint.physicsJoint.distance = maxDistance;
  73116. };
  73117. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  73118. // if (!motorIndex) {
  73119. // joint.physicsJoint.enableMotor();
  73120. // }
  73121. // }
  73122. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  73123. // if (!motorIndex) {
  73124. // joint.physicsJoint.disableMotor();
  73125. // }
  73126. // }
  73127. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73128. if (!motorIndex) {
  73129. joint.physicsJoint.enableMotor();
  73130. joint.physicsJoint.setMotorSpeed(speed);
  73131. if (maxForce) {
  73132. this.setLimit(joint, maxForce);
  73133. }
  73134. }
  73135. };
  73136. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  73137. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  73138. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  73139. };
  73140. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73141. var body = impostor.physicsBody;
  73142. mesh.position.x = body.position.x;
  73143. mesh.position.y = body.position.y;
  73144. mesh.position.z = body.position.z;
  73145. if (mesh.rotationQuaternion) {
  73146. mesh.rotationQuaternion.x = body.quaternion.x;
  73147. mesh.rotationQuaternion.y = body.quaternion.y;
  73148. mesh.rotationQuaternion.z = body.quaternion.z;
  73149. mesh.rotationQuaternion.w = body.quaternion.w;
  73150. }
  73151. };
  73152. CannonJSPlugin.prototype.getRadius = function (impostor) {
  73153. var shape = impostor.physicsBody.shapes[0];
  73154. return shape.boundingSphereRadius;
  73155. };
  73156. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73157. var shape = impostor.physicsBody.shapes[0];
  73158. result.x = shape.halfExtents.x * 2;
  73159. result.y = shape.halfExtents.y * 2;
  73160. result.z = shape.halfExtents.z * 2;
  73161. };
  73162. CannonJSPlugin.prototype.dispose = function () {
  73163. };
  73164. CannonJSPlugin.prototype._extendNamespace = function () {
  73165. //this will force cannon to execute at least one step when using interpolation
  73166. var step_tmp1 = new this.BJSCANNON.Vec3();
  73167. var Engine = this.BJSCANNON;
  73168. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  73169. maxSubSteps = maxSubSteps || 10;
  73170. timeSinceLastCalled = timeSinceLastCalled || 0;
  73171. if (timeSinceLastCalled === 0) {
  73172. this.internalStep(dt);
  73173. this.time += dt;
  73174. }
  73175. else {
  73176. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  73177. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  73178. var t0 = performance.now();
  73179. for (var i = 0; i !== internalSteps; i++) {
  73180. this.internalStep(dt);
  73181. if (performance.now() - t0 > dt * 1000) {
  73182. break;
  73183. }
  73184. }
  73185. this.time += timeSinceLastCalled;
  73186. var h = this.time % dt;
  73187. var h_div_dt = h / dt;
  73188. var interpvelo = step_tmp1;
  73189. var bodies = this.bodies;
  73190. for (var j = 0; j !== bodies.length; j++) {
  73191. var b = bodies[j];
  73192. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  73193. b.position.vsub(b.previousPosition, interpvelo);
  73194. interpvelo.scale(h_div_dt, interpvelo);
  73195. b.position.vadd(interpvelo, b.interpolatedPosition);
  73196. }
  73197. else {
  73198. b.interpolatedPosition.copy(b.position);
  73199. b.interpolatedQuaternion.copy(b.quaternion);
  73200. }
  73201. }
  73202. }
  73203. };
  73204. };
  73205. return CannonJSPlugin;
  73206. }());
  73207. BABYLON.CannonJSPlugin = CannonJSPlugin;
  73208. })(BABYLON || (BABYLON = {}));
  73209. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  73210. var BABYLON;
  73211. (function (BABYLON) {
  73212. var OimoJSPlugin = /** @class */ (function () {
  73213. function OimoJSPlugin(iterations) {
  73214. this.name = "OimoJSPlugin";
  73215. this._tmpImpostorsArray = [];
  73216. this._tmpPositionVector = BABYLON.Vector3.Zero();
  73217. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  73218. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  73219. this.world.worldscale(1);
  73220. this.world.clear();
  73221. //making sure no stats are calculated
  73222. this.world.isNoStat = true;
  73223. }
  73224. OimoJSPlugin.prototype.setGravity = function (gravity) {
  73225. this.world.gravity.copy(gravity);
  73226. };
  73227. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  73228. this.world.timeStep = timeStep;
  73229. };
  73230. OimoJSPlugin.prototype.getTimeStep = function () {
  73231. return this.world.timeStep;
  73232. };
  73233. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  73234. var _this = this;
  73235. impostors.forEach(function (impostor) {
  73236. impostor.beforeStep();
  73237. });
  73238. this.world.step();
  73239. impostors.forEach(function (impostor) {
  73240. impostor.afterStep();
  73241. //update the ordered impostors array
  73242. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  73243. });
  73244. //check for collisions
  73245. var contact = this.world.contacts;
  73246. while (contact !== null) {
  73247. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  73248. contact = contact.next;
  73249. continue;
  73250. }
  73251. //is this body colliding with any other? get the impostor
  73252. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  73253. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  73254. if (!mainImpostor || !collidingImpostor) {
  73255. contact = contact.next;
  73256. continue;
  73257. }
  73258. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  73259. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  73260. contact = contact.next;
  73261. }
  73262. };
  73263. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  73264. var mass = impostor.physicsBody.massInfo.mass;
  73265. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  73266. };
  73267. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  73268. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  73269. this.applyImpulse(impostor, force, contactPoint);
  73270. };
  73271. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  73272. var _this = this;
  73273. //parent-child relationship. Does this impostor has a parent impostor?
  73274. if (impostor.parent) {
  73275. if (impostor.physicsBody) {
  73276. this.removePhysicsBody(impostor);
  73277. //TODO is that needed?
  73278. impostor.forceUpdate();
  73279. }
  73280. return;
  73281. }
  73282. if (impostor.isBodyInitRequired()) {
  73283. var bodyConfig = {
  73284. name: impostor.uniqueId,
  73285. //Oimo must have mass, also for static objects.
  73286. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  73287. size: [],
  73288. type: [],
  73289. pos: [],
  73290. rot: [],
  73291. move: impostor.getParam("mass") !== 0,
  73292. //Supporting older versions of Oimo
  73293. world: this.world
  73294. };
  73295. var impostors = [impostor];
  73296. var addToArray = function (parent) {
  73297. if (!parent.getChildMeshes)
  73298. return;
  73299. parent.getChildMeshes().forEach(function (m) {
  73300. if (m.physicsImpostor) {
  73301. impostors.push(m.physicsImpostor);
  73302. //m.physicsImpostor._init();
  73303. }
  73304. });
  73305. };
  73306. addToArray(impostor.object);
  73307. var checkWithEpsilon_1 = function (value) {
  73308. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  73309. };
  73310. impostors.forEach(function (i) {
  73311. if (!impostor.object.rotationQuaternion) {
  73312. return;
  73313. }
  73314. //get the correct bounding box
  73315. var oldQuaternion = i.object.rotationQuaternion;
  73316. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  73317. x: impostor.object.rotationQuaternion.x,
  73318. y: impostor.object.rotationQuaternion.y,
  73319. z: impostor.object.rotationQuaternion.z,
  73320. s: impostor.object.rotationQuaternion.w
  73321. });
  73322. var extendSize = i.getObjectExtendSize();
  73323. if (i === impostor) {
  73324. var center = impostor.getObjectCenter();
  73325. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  73326. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  73327. //Can also use Array.prototype.push.apply
  73328. bodyConfig.pos.push(center.x);
  73329. bodyConfig.pos.push(center.y);
  73330. bodyConfig.pos.push(center.z);
  73331. //tmp solution
  73332. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73333. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73334. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73335. }
  73336. else {
  73337. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  73338. bodyConfig.pos.push(localPosition.x);
  73339. bodyConfig.pos.push(localPosition.y);
  73340. bodyConfig.pos.push(localPosition.z);
  73341. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  73342. bodyConfig.rot.push(0);
  73343. bodyConfig.rot.push(0);
  73344. bodyConfig.rot.push(0);
  73345. }
  73346. // register mesh
  73347. switch (i.type) {
  73348. case BABYLON.PhysicsImpostor.ParticleImpostor:
  73349. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  73350. case BABYLON.PhysicsImpostor.SphereImpostor:
  73351. var radiusX = extendSize.x;
  73352. var radiusY = extendSize.y;
  73353. var radiusZ = extendSize.z;
  73354. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  73355. bodyConfig.type.push('sphere');
  73356. //due to the way oimo works with compounds, add 3 times
  73357. bodyConfig.size.push(size);
  73358. bodyConfig.size.push(size);
  73359. bodyConfig.size.push(size);
  73360. break;
  73361. case BABYLON.PhysicsImpostor.CylinderImpostor:
  73362. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  73363. var sizeY = checkWithEpsilon_1(extendSize.y);
  73364. bodyConfig.type.push('cylinder');
  73365. bodyConfig.size.push(sizeX);
  73366. bodyConfig.size.push(sizeY);
  73367. //due to the way oimo works with compounds, add one more value.
  73368. bodyConfig.size.push(sizeY);
  73369. break;
  73370. case BABYLON.PhysicsImpostor.PlaneImpostor:
  73371. case BABYLON.PhysicsImpostor.BoxImpostor:
  73372. default:
  73373. var sizeX = checkWithEpsilon_1(extendSize.x);
  73374. var sizeY = checkWithEpsilon_1(extendSize.y);
  73375. var sizeZ = checkWithEpsilon_1(extendSize.z);
  73376. bodyConfig.type.push('box');
  73377. bodyConfig.size.push(sizeX);
  73378. bodyConfig.size.push(sizeY);
  73379. bodyConfig.size.push(sizeZ);
  73380. break;
  73381. }
  73382. //actually not needed, but hey...
  73383. i.object.rotationQuaternion = oldQuaternion;
  73384. });
  73385. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  73386. }
  73387. else {
  73388. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  73389. }
  73390. impostor.setDeltaPosition(this._tmpPositionVector);
  73391. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  73392. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  73393. };
  73394. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73395. //impostor.physicsBody.dispose();
  73396. //Same as : (older oimo versions)
  73397. this.world.removeRigidBody(impostor.physicsBody);
  73398. };
  73399. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73400. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73401. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73402. if (!mainBody || !connectedBody) {
  73403. return;
  73404. }
  73405. var jointData = impostorJoint.joint.jointData;
  73406. var options = jointData.nativeParams || {};
  73407. var type;
  73408. var nativeJointData = {
  73409. body1: mainBody,
  73410. body2: connectedBody,
  73411. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  73412. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  73413. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  73414. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  73415. min: options.min,
  73416. max: options.max,
  73417. collision: options.collision || jointData.collision,
  73418. spring: options.spring,
  73419. //supporting older version of Oimo
  73420. world: this.world
  73421. };
  73422. switch (impostorJoint.joint.type) {
  73423. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  73424. type = "jointBall";
  73425. break;
  73426. case BABYLON.PhysicsJoint.SpringJoint:
  73427. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  73428. var springData = jointData;
  73429. nativeJointData.min = springData.length || nativeJointData.min;
  73430. //Max should also be set, just make sure it is at least min
  73431. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  73432. case BABYLON.PhysicsJoint.DistanceJoint:
  73433. type = "jointDistance";
  73434. nativeJointData.max = jointData.maxDistance;
  73435. break;
  73436. case BABYLON.PhysicsJoint.PrismaticJoint:
  73437. type = "jointPrisme";
  73438. break;
  73439. case BABYLON.PhysicsJoint.SliderJoint:
  73440. type = "jointSlide";
  73441. break;
  73442. case BABYLON.PhysicsJoint.WheelJoint:
  73443. type = "jointWheel";
  73444. break;
  73445. case BABYLON.PhysicsJoint.HingeJoint:
  73446. default:
  73447. type = "jointHinge";
  73448. break;
  73449. }
  73450. nativeJointData.type = type;
  73451. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  73452. };
  73453. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73454. //Bug in Oimo prevents us from disposing a joint in the playground
  73455. //joint.joint.physicsJoint.dispose();
  73456. //So we will bruteforce it!
  73457. try {
  73458. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73459. }
  73460. catch (e) {
  73461. BABYLON.Tools.Warn(e);
  73462. }
  73463. };
  73464. OimoJSPlugin.prototype.isSupported = function () {
  73465. return this.BJSOIMO !== undefined;
  73466. };
  73467. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73468. if (!impostor.physicsBody.sleeping) {
  73469. //TODO check that
  73470. if (impostor.physicsBody.shapes.next) {
  73471. var parentShape = this._getLastShape(impostor.physicsBody);
  73472. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73473. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73474. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73475. }
  73476. else {
  73477. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73478. }
  73479. if (impostor.object.rotationQuaternion) {
  73480. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73481. impostor.object.rotationQuaternion.normalize();
  73482. }
  73483. }
  73484. };
  73485. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73486. var body = impostor.physicsBody;
  73487. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73488. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73489. body.syncShapes();
  73490. body.awake();
  73491. };
  73492. OimoJSPlugin.prototype._getLastShape = function (body) {
  73493. var lastShape = body.shapes;
  73494. while (lastShape.next) {
  73495. lastShape = lastShape.next;
  73496. }
  73497. return lastShape;
  73498. };
  73499. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73500. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73501. };
  73502. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73503. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73504. };
  73505. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73506. var v = impostor.physicsBody.linearVelocity;
  73507. if (!v) {
  73508. return null;
  73509. }
  73510. return new BABYLON.Vector3(v.x, v.y, v.z);
  73511. };
  73512. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73513. var v = impostor.physicsBody.angularVelocity;
  73514. if (!v) {
  73515. return null;
  73516. }
  73517. return new BABYLON.Vector3(v.x, v.y, v.z);
  73518. };
  73519. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73520. var staticBody = mass === 0;
  73521. //this will actually set the body's density and not its mass.
  73522. //But this is how oimo treats the mass variable.
  73523. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73524. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73525. };
  73526. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73527. return impostor.physicsBody.shapes.density;
  73528. };
  73529. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73530. return impostor.physicsBody.shapes.friction;
  73531. };
  73532. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73533. impostor.physicsBody.shapes.friction = friction;
  73534. };
  73535. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73536. return impostor.physicsBody.shapes.restitution;
  73537. };
  73538. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73539. impostor.physicsBody.shapes.restitution = restitution;
  73540. };
  73541. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73542. impostor.physicsBody.sleep();
  73543. };
  73544. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73545. impostor.physicsBody.awake();
  73546. };
  73547. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73548. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73549. if (minDistance !== void 0) {
  73550. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73551. }
  73552. };
  73553. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73554. //TODO separate rotational and transational motors.
  73555. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73556. if (motor) {
  73557. motor.setMotor(speed, maxForce);
  73558. }
  73559. };
  73560. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73561. //TODO separate rotational and transational motors.
  73562. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73563. if (motor) {
  73564. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73565. }
  73566. };
  73567. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73568. var body = impostor.physicsBody;
  73569. mesh.position.x = body.position.x;
  73570. mesh.position.y = body.position.y;
  73571. mesh.position.z = body.position.z;
  73572. if (mesh.rotationQuaternion) {
  73573. mesh.rotationQuaternion.x = body.orientation.x;
  73574. mesh.rotationQuaternion.y = body.orientation.y;
  73575. mesh.rotationQuaternion.z = body.orientation.z;
  73576. mesh.rotationQuaternion.w = body.orientation.s;
  73577. }
  73578. };
  73579. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73580. return impostor.physicsBody.shapes.radius;
  73581. };
  73582. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73583. var shape = impostor.physicsBody.shapes;
  73584. result.x = shape.halfWidth * 2;
  73585. result.y = shape.halfHeight * 2;
  73586. result.z = shape.halfDepth * 2;
  73587. };
  73588. OimoJSPlugin.prototype.dispose = function () {
  73589. this.world.clear();
  73590. };
  73591. return OimoJSPlugin;
  73592. }());
  73593. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73594. })(BABYLON || (BABYLON = {}));
  73595. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73596. var BABYLON;
  73597. (function (BABYLON) {
  73598. /*
  73599. * Based on jsTGALoader - Javascript loader for TGA file
  73600. * By Vincent Thibault
  73601. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73602. */
  73603. var TGATools = /** @class */ (function () {
  73604. function TGATools() {
  73605. }
  73606. TGATools.GetTGAHeader = function (data) {
  73607. var offset = 0;
  73608. var header = {
  73609. id_length: data[offset++],
  73610. colormap_type: data[offset++],
  73611. image_type: data[offset++],
  73612. colormap_index: data[offset++] | data[offset++] << 8,
  73613. colormap_length: data[offset++] | data[offset++] << 8,
  73614. colormap_size: data[offset++],
  73615. origin: [
  73616. data[offset++] | data[offset++] << 8,
  73617. data[offset++] | data[offset++] << 8
  73618. ],
  73619. width: data[offset++] | data[offset++] << 8,
  73620. height: data[offset++] | data[offset++] << 8,
  73621. pixel_size: data[offset++],
  73622. flags: data[offset++]
  73623. };
  73624. return header;
  73625. };
  73626. TGATools.UploadContent = function (gl, data) {
  73627. // Not enough data to contain header ?
  73628. if (data.length < 19) {
  73629. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73630. return;
  73631. }
  73632. // Read Header
  73633. var offset = 18;
  73634. var header = TGATools.GetTGAHeader(data);
  73635. // Assume it's a valid Targa file.
  73636. if (header.id_length + offset > data.length) {
  73637. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73638. return;
  73639. }
  73640. // Skip not needed data
  73641. offset += header.id_length;
  73642. var use_rle = false;
  73643. var use_pal = false;
  73644. var use_grey = false;
  73645. // Get some informations.
  73646. switch (header.image_type) {
  73647. case TGATools._TYPE_RLE_INDEXED:
  73648. use_rle = true;
  73649. case TGATools._TYPE_INDEXED:
  73650. use_pal = true;
  73651. break;
  73652. case TGATools._TYPE_RLE_RGB:
  73653. use_rle = true;
  73654. case TGATools._TYPE_RGB:
  73655. // use_rgb = true;
  73656. break;
  73657. case TGATools._TYPE_RLE_GREY:
  73658. use_rle = true;
  73659. case TGATools._TYPE_GREY:
  73660. use_grey = true;
  73661. break;
  73662. }
  73663. var pixel_data;
  73664. // var numAlphaBits = header.flags & 0xf;
  73665. var pixel_size = header.pixel_size >> 3;
  73666. var pixel_total = header.width * header.height * pixel_size;
  73667. // Read palettes
  73668. var palettes;
  73669. if (use_pal) {
  73670. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73671. }
  73672. // Read LRE
  73673. if (use_rle) {
  73674. pixel_data = new Uint8Array(pixel_total);
  73675. var c, count, i;
  73676. var localOffset = 0;
  73677. var pixels = new Uint8Array(pixel_size);
  73678. while (offset < pixel_total && localOffset < pixel_total) {
  73679. c = data[offset++];
  73680. count = (c & 0x7f) + 1;
  73681. // RLE pixels
  73682. if (c & 0x80) {
  73683. // Bind pixel tmp array
  73684. for (i = 0; i < pixel_size; ++i) {
  73685. pixels[i] = data[offset++];
  73686. }
  73687. // Copy pixel array
  73688. for (i = 0; i < count; ++i) {
  73689. pixel_data.set(pixels, localOffset + i * pixel_size);
  73690. }
  73691. localOffset += pixel_size * count;
  73692. }
  73693. else {
  73694. count *= pixel_size;
  73695. for (i = 0; i < count; ++i) {
  73696. pixel_data[localOffset + i] = data[offset++];
  73697. }
  73698. localOffset += count;
  73699. }
  73700. }
  73701. }
  73702. else {
  73703. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73704. }
  73705. // Load to texture
  73706. var x_start, y_start, x_step, y_step, y_end, x_end;
  73707. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73708. default:
  73709. case TGATools._ORIGIN_UL:
  73710. x_start = 0;
  73711. x_step = 1;
  73712. x_end = header.width;
  73713. y_start = 0;
  73714. y_step = 1;
  73715. y_end = header.height;
  73716. break;
  73717. case TGATools._ORIGIN_BL:
  73718. x_start = 0;
  73719. x_step = 1;
  73720. x_end = header.width;
  73721. y_start = header.height - 1;
  73722. y_step = -1;
  73723. y_end = -1;
  73724. break;
  73725. case TGATools._ORIGIN_UR:
  73726. x_start = header.width - 1;
  73727. x_step = -1;
  73728. x_end = -1;
  73729. y_start = 0;
  73730. y_step = 1;
  73731. y_end = header.height;
  73732. break;
  73733. case TGATools._ORIGIN_BR:
  73734. x_start = header.width - 1;
  73735. x_step = -1;
  73736. x_end = -1;
  73737. y_start = header.height - 1;
  73738. y_step = -1;
  73739. y_end = -1;
  73740. break;
  73741. }
  73742. // Load the specify method
  73743. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73744. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73745. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73746. };
  73747. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73748. var image = pixel_data, colormap = palettes;
  73749. var width = header.width, height = header.height;
  73750. var color, i = 0, x, y;
  73751. var imageData = new Uint8Array(width * height * 4);
  73752. for (y = y_start; y !== y_end; y += y_step) {
  73753. for (x = x_start; x !== x_end; x += x_step, i++) {
  73754. color = image[i];
  73755. imageData[(x + width * y) * 4 + 3] = 255;
  73756. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73757. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73758. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73759. }
  73760. }
  73761. return imageData;
  73762. };
  73763. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73764. var image = pixel_data;
  73765. var width = header.width, height = header.height;
  73766. var color, i = 0, x, y;
  73767. var imageData = new Uint8Array(width * height * 4);
  73768. for (y = y_start; y !== y_end; y += y_step) {
  73769. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73770. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  73771. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  73772. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  73773. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  73774. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  73775. }
  73776. }
  73777. return imageData;
  73778. };
  73779. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73780. var image = pixel_data;
  73781. var width = header.width, height = header.height;
  73782. var i = 0, x, y;
  73783. var imageData = new Uint8Array(width * height * 4);
  73784. for (y = y_start; y !== y_end; y += y_step) {
  73785. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  73786. imageData[(x + width * y) * 4 + 3] = 255;
  73787. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73788. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73789. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73790. }
  73791. }
  73792. return imageData;
  73793. };
  73794. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73795. var image = pixel_data;
  73796. var width = header.width, height = header.height;
  73797. var i = 0, x, y;
  73798. var imageData = new Uint8Array(width * height * 4);
  73799. for (y = y_start; y !== y_end; y += y_step) {
  73800. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  73801. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73802. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73803. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73804. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  73805. }
  73806. }
  73807. return imageData;
  73808. };
  73809. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73810. var image = pixel_data;
  73811. var width = header.width, height = header.height;
  73812. var color, i = 0, x, y;
  73813. var imageData = new Uint8Array(width * height * 4);
  73814. for (y = y_start; y !== y_end; y += y_step) {
  73815. for (x = x_start; x !== x_end; x += x_step, i++) {
  73816. color = image[i];
  73817. imageData[(x + width * y) * 4 + 0] = color;
  73818. imageData[(x + width * y) * 4 + 1] = color;
  73819. imageData[(x + width * y) * 4 + 2] = color;
  73820. imageData[(x + width * y) * 4 + 3] = 255;
  73821. }
  73822. }
  73823. return imageData;
  73824. };
  73825. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73826. var image = pixel_data;
  73827. var width = header.width, height = header.height;
  73828. var i = 0, x, y;
  73829. var imageData = new Uint8Array(width * height * 4);
  73830. for (y = y_start; y !== y_end; y += y_step) {
  73831. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73832. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  73833. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  73834. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73835. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  73836. }
  73837. }
  73838. return imageData;
  73839. };
  73840. //private static _TYPE_NO_DATA = 0;
  73841. TGATools._TYPE_INDEXED = 1;
  73842. TGATools._TYPE_RGB = 2;
  73843. TGATools._TYPE_GREY = 3;
  73844. TGATools._TYPE_RLE_INDEXED = 9;
  73845. TGATools._TYPE_RLE_RGB = 10;
  73846. TGATools._TYPE_RLE_GREY = 11;
  73847. TGATools._ORIGIN_MASK = 0x30;
  73848. TGATools._ORIGIN_SHIFT = 0x04;
  73849. TGATools._ORIGIN_BL = 0x00;
  73850. TGATools._ORIGIN_BR = 0x01;
  73851. TGATools._ORIGIN_UL = 0x02;
  73852. TGATools._ORIGIN_UR = 0x03;
  73853. return TGATools;
  73854. }());
  73855. BABYLON.TGATools = TGATools;
  73856. })(BABYLON || (BABYLON = {}));
  73857. //# sourceMappingURL=babylon.tga.js.map
  73858. var BABYLON;
  73859. (function (BABYLON) {
  73860. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  73861. // All values and structures referenced from:
  73862. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  73863. var DDS_MAGIC = 0x20534444;
  73864. var
  73865. //DDSD_CAPS = 0x1,
  73866. //DDSD_HEIGHT = 0x2,
  73867. //DDSD_WIDTH = 0x4,
  73868. //DDSD_PITCH = 0x8,
  73869. //DDSD_PIXELFORMAT = 0x1000,
  73870. DDSD_MIPMAPCOUNT = 0x20000;
  73871. //DDSD_LINEARSIZE = 0x80000,
  73872. //DDSD_DEPTH = 0x800000;
  73873. // var DDSCAPS_COMPLEX = 0x8,
  73874. // DDSCAPS_MIPMAP = 0x400000,
  73875. // DDSCAPS_TEXTURE = 0x1000;
  73876. var DDSCAPS2_CUBEMAP = 0x200;
  73877. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  73878. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  73879. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  73880. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  73881. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  73882. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  73883. // DDSCAPS2_VOLUME = 0x200000;
  73884. var
  73885. //DDPF_ALPHAPIXELS = 0x1,
  73886. //DDPF_ALPHA = 0x2,
  73887. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  73888. //DDPF_YUV = 0x200,
  73889. DDPF_LUMINANCE = 0x20000;
  73890. function FourCCToInt32(value) {
  73891. return value.charCodeAt(0) +
  73892. (value.charCodeAt(1) << 8) +
  73893. (value.charCodeAt(2) << 16) +
  73894. (value.charCodeAt(3) << 24);
  73895. }
  73896. function Int32ToFourCC(value) {
  73897. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  73898. }
  73899. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  73900. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  73901. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  73902. var FOURCC_DX10 = FourCCToInt32("DX10");
  73903. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  73904. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  73905. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  73906. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  73907. var headerLengthInt = 31; // The header length in 32 bit ints
  73908. // Offsets into the header array
  73909. var off_magic = 0;
  73910. var off_size = 1;
  73911. var off_flags = 2;
  73912. var off_height = 3;
  73913. var off_width = 4;
  73914. var off_mipmapCount = 7;
  73915. var off_pfFlags = 20;
  73916. var off_pfFourCC = 21;
  73917. var off_RGBbpp = 22;
  73918. var off_RMask = 23;
  73919. var off_GMask = 24;
  73920. var off_BMask = 25;
  73921. var off_AMask = 26;
  73922. // var off_caps1 = 27;
  73923. var off_caps2 = 28;
  73924. // var off_caps3 = 29;
  73925. // var off_caps4 = 30;
  73926. var off_dxgiFormat = 32;
  73927. ;
  73928. var DDSTools = /** @class */ (function () {
  73929. function DDSTools() {
  73930. }
  73931. DDSTools.GetDDSInfo = function (arrayBuffer) {
  73932. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73933. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  73934. var mipmapCount = 1;
  73935. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  73936. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73937. }
  73938. var fourCC = header[off_pfFourCC];
  73939. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  73940. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73941. switch (fourCC) {
  73942. case FOURCC_D3DFMT_R16G16B16A16F:
  73943. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73944. break;
  73945. case FOURCC_D3DFMT_R32G32B32A32F:
  73946. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73947. break;
  73948. case FOURCC_DX10:
  73949. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  73950. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73951. break;
  73952. }
  73953. }
  73954. return {
  73955. width: header[off_width],
  73956. height: header[off_height],
  73957. mipmapCount: mipmapCount,
  73958. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  73959. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  73960. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  73961. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  73962. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  73963. dxgiFormat: dxgiFormat,
  73964. textureType: textureType
  73965. };
  73966. };
  73967. DDSTools._ToHalfFloat = function (value) {
  73968. if (!DDSTools._FloatView) {
  73969. DDSTools._FloatView = new Float32Array(1);
  73970. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  73971. }
  73972. DDSTools._FloatView[0] = value;
  73973. var x = DDSTools._Int32View[0];
  73974. var bits = (x >> 16) & 0x8000; /* Get the sign */
  73975. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  73976. var e = (x >> 23) & 0xff; /* Using int is faster here */
  73977. /* If zero, or denormal, or exponent underflows too much for a denormal
  73978. * half, return signed zero. */
  73979. if (e < 103) {
  73980. return bits;
  73981. }
  73982. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  73983. if (e > 142) {
  73984. bits |= 0x7c00;
  73985. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  73986. * not Inf, so make sure we set one mantissa bit too. */
  73987. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  73988. return bits;
  73989. }
  73990. /* If exponent underflows but not too much, return a denormal */
  73991. if (e < 113) {
  73992. m |= 0x0800;
  73993. /* Extra rounding may overflow and set mantissa to 0 and exponent
  73994. * to 1, which is OK. */
  73995. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  73996. return bits;
  73997. }
  73998. bits |= ((e - 112) << 10) | (m >> 1);
  73999. bits += m & 1;
  74000. return bits;
  74001. };
  74002. DDSTools._FromHalfFloat = function (value) {
  74003. var s = (value & 0x8000) >> 15;
  74004. var e = (value & 0x7C00) >> 10;
  74005. var f = value & 0x03FF;
  74006. if (e === 0) {
  74007. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  74008. }
  74009. else if (e == 0x1F) {
  74010. return f ? NaN : ((s ? -1 : 1) * Infinity);
  74011. }
  74012. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  74013. };
  74014. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74015. var destArray = new Float32Array(dataLength);
  74016. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74017. var index = 0;
  74018. for (var y = 0; y < height; y++) {
  74019. for (var x = 0; x < width; x++) {
  74020. var srcPos = (x + y * width) * 4;
  74021. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  74022. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  74023. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  74024. if (DDSTools.StoreLODInAlphaChannel) {
  74025. destArray[index + 3] = lod;
  74026. }
  74027. else {
  74028. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  74029. }
  74030. index += 4;
  74031. }
  74032. }
  74033. return destArray;
  74034. };
  74035. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74036. if (DDSTools.StoreLODInAlphaChannel) {
  74037. var destArray = new Uint16Array(dataLength);
  74038. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74039. var index = 0;
  74040. for (var y = 0; y < height; y++) {
  74041. for (var x = 0; x < width; x++) {
  74042. var srcPos = (x + y * width) * 4;
  74043. destArray[index] = srcData[srcPos];
  74044. destArray[index + 1] = srcData[srcPos + 1];
  74045. destArray[index + 2] = srcData[srcPos + 2];
  74046. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  74047. index += 4;
  74048. }
  74049. }
  74050. return destArray;
  74051. }
  74052. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  74053. };
  74054. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74055. if (DDSTools.StoreLODInAlphaChannel) {
  74056. var destArray = new Float32Array(dataLength);
  74057. var srcData = new Float32Array(arrayBuffer, dataOffset);
  74058. var index = 0;
  74059. for (var y = 0; y < height; y++) {
  74060. for (var x = 0; x < width; x++) {
  74061. var srcPos = (x + y * width) * 4;
  74062. destArray[index] = srcData[srcPos];
  74063. destArray[index + 1] = srcData[srcPos + 1];
  74064. destArray[index + 2] = srcData[srcPos + 2];
  74065. destArray[index + 3] = lod;
  74066. index += 4;
  74067. }
  74068. }
  74069. return destArray;
  74070. }
  74071. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  74072. };
  74073. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74074. var destArray = new Uint8Array(dataLength);
  74075. var srcData = new Float32Array(arrayBuffer, dataOffset);
  74076. var index = 0;
  74077. for (var y = 0; y < height; y++) {
  74078. for (var x = 0; x < width; x++) {
  74079. var srcPos = (x + y * width) * 4;
  74080. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  74081. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  74082. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  74083. if (DDSTools.StoreLODInAlphaChannel) {
  74084. destArray[index + 3] = lod;
  74085. }
  74086. else {
  74087. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  74088. }
  74089. index += 4;
  74090. }
  74091. }
  74092. return destArray;
  74093. };
  74094. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74095. var destArray = new Uint8Array(dataLength);
  74096. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74097. var index = 0;
  74098. for (var y = 0; y < height; y++) {
  74099. for (var x = 0; x < width; x++) {
  74100. var srcPos = (x + y * width) * 4;
  74101. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  74102. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  74103. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  74104. if (DDSTools.StoreLODInAlphaChannel) {
  74105. destArray[index + 3] = lod;
  74106. }
  74107. else {
  74108. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  74109. }
  74110. index += 4;
  74111. }
  74112. }
  74113. return destArray;
  74114. };
  74115. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  74116. var byteArray = new Uint8Array(dataLength);
  74117. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74118. var index = 0;
  74119. for (var y = 0; y < height; y++) {
  74120. for (var x = 0; x < width; x++) {
  74121. var srcPos = (x + y * width) * 4;
  74122. byteArray[index] = srcData[srcPos + rOffset];
  74123. byteArray[index + 1] = srcData[srcPos + gOffset];
  74124. byteArray[index + 2] = srcData[srcPos + bOffset];
  74125. byteArray[index + 3] = srcData[srcPos + aOffset];
  74126. index += 4;
  74127. }
  74128. }
  74129. return byteArray;
  74130. };
  74131. DDSTools._ExtractLongWordOrder = function (value) {
  74132. if (value === 0 || value === 255 || value === -16777216) {
  74133. return 0;
  74134. }
  74135. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  74136. };
  74137. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  74138. var byteArray = new Uint8Array(dataLength);
  74139. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74140. var index = 0;
  74141. for (var y = 0; y < height; y++) {
  74142. for (var x = 0; x < width; x++) {
  74143. var srcPos = (x + y * width) * 3;
  74144. byteArray[index] = srcData[srcPos + rOffset];
  74145. byteArray[index + 1] = srcData[srcPos + gOffset];
  74146. byteArray[index + 2] = srcData[srcPos + bOffset];
  74147. index += 3;
  74148. }
  74149. }
  74150. return byteArray;
  74151. };
  74152. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  74153. var byteArray = new Uint8Array(dataLength);
  74154. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74155. var index = 0;
  74156. for (var y = 0; y < height; y++) {
  74157. for (var x = 0; x < width; x++) {
  74158. var srcPos = (x + y * width);
  74159. byteArray[index] = srcData[srcPos];
  74160. index++;
  74161. }
  74162. }
  74163. return byteArray;
  74164. };
  74165. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  74166. if (lodIndex === void 0) { lodIndex = -1; }
  74167. var ext = engine.getCaps().s3tc;
  74168. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  74169. var fourCC, width, height, dataLength = 0, dataOffset;
  74170. var byteArray, mipmapCount, mip;
  74171. var internalFormat = 0;
  74172. var format = 0;
  74173. var blockBytes = 1;
  74174. if (header[off_magic] !== DDS_MAGIC) {
  74175. BABYLON.Tools.Error("Invalid magic number in DDS header");
  74176. return;
  74177. }
  74178. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  74179. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  74180. return;
  74181. }
  74182. if (info.isCompressed && !ext) {
  74183. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  74184. return;
  74185. }
  74186. var bpp = header[off_RGBbpp];
  74187. dataOffset = header[off_size] + 4;
  74188. var computeFormats = false;
  74189. if (info.isFourCC) {
  74190. fourCC = header[off_pfFourCC];
  74191. switch (fourCC) {
  74192. case FOURCC_DXT1:
  74193. blockBytes = 8;
  74194. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  74195. break;
  74196. case FOURCC_DXT3:
  74197. blockBytes = 16;
  74198. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  74199. break;
  74200. case FOURCC_DXT5:
  74201. blockBytes = 16;
  74202. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  74203. break;
  74204. case FOURCC_D3DFMT_R16G16B16A16F:
  74205. computeFormats = true;
  74206. break;
  74207. case FOURCC_D3DFMT_R32G32B32A32F:
  74208. computeFormats = true;
  74209. break;
  74210. case FOURCC_DX10:
  74211. // There is an additionnal header so dataOffset need to be changed
  74212. dataOffset += 5 * 4; // 5 uints
  74213. var supported = false;
  74214. switch (info.dxgiFormat) {
  74215. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  74216. computeFormats = true;
  74217. supported = true;
  74218. break;
  74219. case DXGI_FORMAT_B8G8R8X8_UNORM:
  74220. info.isRGB = true;
  74221. info.isFourCC = false;
  74222. bpp = 32;
  74223. supported = true;
  74224. break;
  74225. }
  74226. if (supported) {
  74227. break;
  74228. }
  74229. default:
  74230. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  74231. return;
  74232. }
  74233. }
  74234. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  74235. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  74236. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  74237. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  74238. if (computeFormats) {
  74239. format = engine._getWebGLTextureType(info.textureType);
  74240. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74241. }
  74242. mipmapCount = 1;
  74243. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  74244. mipmapCount = Math.max(1, header[off_mipmapCount]);
  74245. }
  74246. for (var face = 0; face < faces; face++) {
  74247. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  74248. width = header[off_width];
  74249. height = header[off_height];
  74250. for (mip = 0; mip < mipmapCount; ++mip) {
  74251. if (lodIndex === -1 || lodIndex === mip) {
  74252. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  74253. var i = (lodIndex === -1) ? mip : 0;
  74254. if (!info.isCompressed && info.isFourCC) {
  74255. dataLength = width * height * 4;
  74256. var floatArray = null;
  74257. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  74258. if (bpp === 128) {
  74259. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74260. }
  74261. else if (bpp === 64) {
  74262. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74263. }
  74264. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74265. format = engine._getWebGLTextureType(info.textureType);
  74266. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74267. }
  74268. else {
  74269. if (bpp === 128) {
  74270. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74271. }
  74272. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  74273. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74274. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74275. format = engine._getWebGLTextureType(info.textureType);
  74276. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74277. }
  74278. else {
  74279. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74280. }
  74281. }
  74282. if (floatArray) {
  74283. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  74284. }
  74285. }
  74286. else if (info.isRGB) {
  74287. if (bpp === 24) {
  74288. dataLength = width * height * 3;
  74289. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  74290. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  74291. }
  74292. else {
  74293. dataLength = width * height * 4;
  74294. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  74295. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  74296. }
  74297. }
  74298. else if (info.isLuminance) {
  74299. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  74300. var unpaddedRowSize = width;
  74301. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  74302. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  74303. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  74304. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  74305. }
  74306. else {
  74307. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  74308. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  74309. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  74310. }
  74311. }
  74312. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  74313. width *= 0.5;
  74314. height *= 0.5;
  74315. width = Math.max(1.0, width);
  74316. height = Math.max(1.0, height);
  74317. }
  74318. if (currentFace !== undefined) {
  74319. // Loading a single face
  74320. break;
  74321. }
  74322. }
  74323. };
  74324. DDSTools.StoreLODInAlphaChannel = false;
  74325. return DDSTools;
  74326. }());
  74327. BABYLON.DDSTools = DDSTools;
  74328. })(BABYLON || (BABYLON = {}));
  74329. //# sourceMappingURL=babylon.dds.js.map
  74330. var BABYLON;
  74331. (function (BABYLON) {
  74332. /**
  74333. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  74334. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  74335. */
  74336. var KhronosTextureContainer = /** @class */ (function () {
  74337. /**
  74338. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  74339. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  74340. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  74341. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  74342. */
  74343. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  74344. this.arrayBuffer = arrayBuffer;
  74345. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  74346. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  74347. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  74348. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  74349. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  74350. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  74351. BABYLON.Tools.Error("texture missing KTX identifier");
  74352. return;
  74353. }
  74354. // load the reset of the header in native 32 bit int
  74355. var header = new Int32Array(this.arrayBuffer, 12, 13);
  74356. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  74357. var oppositeEndianess = header[0] === 0x01020304;
  74358. // read all the header elements in order they exist in the file, without modification (sans endainness)
  74359. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  74360. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  74361. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  74362. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  74363. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  74364. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  74365. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  74366. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  74367. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  74368. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  74369. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  74370. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  74371. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  74372. if (this.glType !== 0) {
  74373. BABYLON.Tools.Error("only compressed formats currently supported");
  74374. return;
  74375. }
  74376. else {
  74377. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  74378. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  74379. }
  74380. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  74381. BABYLON.Tools.Error("only 2D textures currently supported");
  74382. return;
  74383. }
  74384. if (this.numberOfArrayElements !== 0) {
  74385. BABYLON.Tools.Error("texture arrays not currently supported");
  74386. return;
  74387. }
  74388. if (this.numberOfFaces !== facesExpected) {
  74389. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  74390. return;
  74391. }
  74392. // we now have a completely validated file, so could use existence of loadType as success
  74393. // would need to make this more elaborate & adjust checks above to support more than one load type
  74394. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  74395. }
  74396. // not as fast hardware based, but will probably never need to use
  74397. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  74398. return ((val & 0xFF) << 24)
  74399. | ((val & 0xFF00) << 8)
  74400. | ((val >> 8) & 0xFF00)
  74401. | ((val >> 24) & 0xFF);
  74402. };
  74403. /**
  74404. * It is assumed that the texture has already been created & is currently bound
  74405. */
  74406. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  74407. switch (this.loadType) {
  74408. case KhronosTextureContainer.COMPRESSED_2D:
  74409. this._upload2DCompressedLevels(gl, loadMipmaps);
  74410. break;
  74411. case KhronosTextureContainer.TEX_2D:
  74412. case KhronosTextureContainer.COMPRESSED_3D:
  74413. case KhronosTextureContainer.TEX_3D:
  74414. }
  74415. };
  74416. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  74417. // initialize width & height for level 1
  74418. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  74419. var width = this.pixelWidth;
  74420. var height = this.pixelHeight;
  74421. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  74422. for (var level = 0; level < mipmapCount; level++) {
  74423. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  74424. for (var face = 0; face < this.numberOfFaces; face++) {
  74425. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  74426. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  74427. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  74428. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  74429. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  74430. }
  74431. width = Math.max(1.0, width * 0.5);
  74432. height = Math.max(1.0, height * 0.5);
  74433. }
  74434. };
  74435. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  74436. // load types
  74437. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  74438. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  74439. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  74440. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  74441. return KhronosTextureContainer;
  74442. }());
  74443. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  74444. })(BABYLON || (BABYLON = {}));
  74445. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  74446. var BABYLON;
  74447. (function (BABYLON) {
  74448. var Debug = /** @class */ (function () {
  74449. function Debug() {
  74450. }
  74451. Debug.AxesViewer = /** @class */ (function () {
  74452. function AxesViewer(scene, scaleLines) {
  74453. if (scaleLines === void 0) { scaleLines = 1; }
  74454. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74455. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74456. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74457. this.scaleLines = 1;
  74458. this.scaleLines = scaleLines;
  74459. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74460. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74461. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74462. this._xmesh.renderingGroupId = 2;
  74463. this._ymesh.renderingGroupId = 2;
  74464. this._zmesh.renderingGroupId = 2;
  74465. this._xmesh.material.checkReadyOnlyOnce = true;
  74466. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74467. this._ymesh.material.checkReadyOnlyOnce = true;
  74468. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74469. this._zmesh.material.checkReadyOnlyOnce = true;
  74470. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74471. this.scene = scene;
  74472. }
  74473. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74474. var scaleLines = this.scaleLines;
  74475. if (this._xmesh) {
  74476. this._xmesh.position.copyFrom(position);
  74477. }
  74478. if (this._ymesh) {
  74479. this._ymesh.position.copyFrom(position);
  74480. }
  74481. if (this._zmesh) {
  74482. this._zmesh.position.copyFrom(position);
  74483. }
  74484. var point2 = this._xline[1];
  74485. point2.x = xaxis.x * scaleLines;
  74486. point2.y = xaxis.y * scaleLines;
  74487. point2.z = xaxis.z * scaleLines;
  74488. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74489. point2 = this._yline[1];
  74490. point2.x = yaxis.x * scaleLines;
  74491. point2.y = yaxis.y * scaleLines;
  74492. point2.z = yaxis.z * scaleLines;
  74493. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74494. point2 = this._zline[1];
  74495. point2.x = zaxis.x * scaleLines;
  74496. point2.y = zaxis.y * scaleLines;
  74497. point2.z = zaxis.z * scaleLines;
  74498. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74499. };
  74500. AxesViewer.prototype.dispose = function () {
  74501. if (this._xmesh) {
  74502. this._xmesh.dispose();
  74503. }
  74504. if (this._ymesh) {
  74505. this._ymesh.dispose();
  74506. }
  74507. if (this._zmesh) {
  74508. this._zmesh.dispose();
  74509. }
  74510. this._xmesh = null;
  74511. this._ymesh = null;
  74512. this._zmesh = null;
  74513. this.scene = null;
  74514. };
  74515. return AxesViewer;
  74516. }());
  74517. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74518. __extends(BoneAxesViewer, _super);
  74519. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74520. if (scaleLines === void 0) { scaleLines = 1; }
  74521. var _this = _super.call(this, scene, scaleLines) || this;
  74522. _this.pos = BABYLON.Vector3.Zero();
  74523. _this.xaxis = BABYLON.Vector3.Zero();
  74524. _this.yaxis = BABYLON.Vector3.Zero();
  74525. _this.zaxis = BABYLON.Vector3.Zero();
  74526. _this.mesh = mesh;
  74527. _this.bone = bone;
  74528. return _this;
  74529. }
  74530. BoneAxesViewer.prototype.update = function () {
  74531. if (!this.mesh || !this.bone) {
  74532. return;
  74533. }
  74534. var bone = this.bone;
  74535. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74536. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74537. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74538. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74539. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74540. };
  74541. BoneAxesViewer.prototype.dispose = function () {
  74542. if (this.mesh) {
  74543. this.mesh = null;
  74544. this.bone = null;
  74545. _super.prototype.dispose.call(this);
  74546. }
  74547. };
  74548. return BoneAxesViewer;
  74549. }(Debug.AxesViewer));
  74550. Debug.PhysicsViewer = /** @class */ (function () {
  74551. function PhysicsViewer(scene) {
  74552. this._impostors = [];
  74553. this._meshes = [];
  74554. this._numMeshes = 0;
  74555. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74556. var physicEngine = this._scene.getPhysicsEngine();
  74557. if (physicEngine) {
  74558. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74559. }
  74560. }
  74561. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74562. var plugin = this._physicsEnginePlugin;
  74563. for (var i = 0; i < this._numMeshes; i++) {
  74564. var impostor = this._impostors[i];
  74565. if (!impostor) {
  74566. continue;
  74567. }
  74568. if (impostor.isDisposed) {
  74569. this.hideImpostor(this._impostors[i--]);
  74570. }
  74571. else {
  74572. var mesh = this._meshes[i];
  74573. if (mesh && plugin) {
  74574. plugin.syncMeshWithImpostor(mesh, impostor);
  74575. }
  74576. }
  74577. }
  74578. };
  74579. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74580. if (!this._scene) {
  74581. return;
  74582. }
  74583. for (var i = 0; i < this._numMeshes; i++) {
  74584. if (this._impostors[i] == impostor) {
  74585. return;
  74586. }
  74587. }
  74588. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74589. if (debugMesh) {
  74590. this._impostors[this._numMeshes] = impostor;
  74591. this._meshes[this._numMeshes] = debugMesh;
  74592. if (this._numMeshes === 0) {
  74593. this._renderFunction = this._updateDebugMeshes.bind(this);
  74594. this._scene.registerBeforeRender(this._renderFunction);
  74595. }
  74596. this._numMeshes++;
  74597. }
  74598. };
  74599. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74600. if (!impostor || !this._scene) {
  74601. return;
  74602. }
  74603. var removed = false;
  74604. for (var i = 0; i < this._numMeshes; i++) {
  74605. if (this._impostors[i] == impostor) {
  74606. var mesh = this._meshes[i];
  74607. if (!mesh) {
  74608. continue;
  74609. }
  74610. this._scene.removeMesh(mesh);
  74611. mesh.dispose();
  74612. this._numMeshes--;
  74613. if (this._numMeshes > 0) {
  74614. this._meshes[i] = this._meshes[this._numMeshes];
  74615. this._impostors[i] = this._impostors[this._numMeshes];
  74616. this._meshes[this._numMeshes] = null;
  74617. this._impostors[this._numMeshes] = null;
  74618. }
  74619. else {
  74620. this._meshes[0] = null;
  74621. this._impostors[0] = null;
  74622. }
  74623. removed = true;
  74624. break;
  74625. }
  74626. }
  74627. if (removed && this._numMeshes === 0) {
  74628. this._scene.unregisterBeforeRender(this._renderFunction);
  74629. }
  74630. };
  74631. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74632. if (!this._debugMaterial) {
  74633. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74634. this._debugMaterial.wireframe = true;
  74635. }
  74636. return this._debugMaterial;
  74637. };
  74638. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74639. if (!this._debugBoxMesh) {
  74640. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74641. this._debugBoxMesh.renderingGroupId = 1;
  74642. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74643. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74644. scene.removeMesh(this._debugBoxMesh);
  74645. }
  74646. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74647. };
  74648. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74649. if (!this._debugSphereMesh) {
  74650. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74651. this._debugSphereMesh.renderingGroupId = 1;
  74652. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74653. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74654. scene.removeMesh(this._debugSphereMesh);
  74655. }
  74656. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74657. };
  74658. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74659. var mesh = null;
  74660. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74661. mesh = this._getDebugBoxMesh(scene);
  74662. impostor.getBoxSizeToRef(mesh.scaling);
  74663. }
  74664. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74665. mesh = this._getDebugSphereMesh(scene);
  74666. var radius = impostor.getRadius();
  74667. mesh.scaling.x = radius * 2;
  74668. mesh.scaling.y = radius * 2;
  74669. mesh.scaling.z = radius * 2;
  74670. }
  74671. return mesh;
  74672. };
  74673. PhysicsViewer.prototype.dispose = function () {
  74674. for (var i = 0; i < this._numMeshes; i++) {
  74675. this.hideImpostor(this._impostors[i]);
  74676. }
  74677. if (this._debugBoxMesh) {
  74678. this._debugBoxMesh.dispose();
  74679. }
  74680. if (this._debugSphereMesh) {
  74681. this._debugSphereMesh.dispose();
  74682. }
  74683. if (this._debugMaterial) {
  74684. this._debugMaterial.dispose();
  74685. }
  74686. this._impostors.length = 0;
  74687. this._scene = null;
  74688. this._physicsEnginePlugin = null;
  74689. };
  74690. return PhysicsViewer;
  74691. }());
  74692. Debug.SkeletonViewer = /** @class */ (function () {
  74693. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74694. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74695. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74696. this.skeleton = skeleton;
  74697. this.mesh = mesh;
  74698. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74699. this.renderingGroupId = renderingGroupId;
  74700. this.color = BABYLON.Color3.White();
  74701. this._debugLines = new Array();
  74702. this._isEnabled = false;
  74703. this._scene = scene;
  74704. this.update();
  74705. this._renderFunction = this.update.bind(this);
  74706. }
  74707. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74708. get: function () {
  74709. return this._isEnabled;
  74710. },
  74711. set: function (value) {
  74712. if (this._isEnabled === value) {
  74713. return;
  74714. }
  74715. this._isEnabled = value;
  74716. if (value) {
  74717. this._scene.registerBeforeRender(this._renderFunction);
  74718. }
  74719. else {
  74720. this._scene.unregisterBeforeRender(this._renderFunction);
  74721. }
  74722. },
  74723. enumerable: true,
  74724. configurable: true
  74725. });
  74726. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74727. if (x === void 0) { x = 0; }
  74728. if (y === void 0) { y = 0; }
  74729. if (z === void 0) { z = 0; }
  74730. var tmat = BABYLON.Tmp.Matrix[0];
  74731. var parentBone = bone.getParent();
  74732. tmat.copyFrom(bone.getLocalMatrix());
  74733. if (x !== 0 || y !== 0 || z !== 0) {
  74734. var tmat2 = BABYLON.Tmp.Matrix[1];
  74735. BABYLON.Matrix.IdentityToRef(tmat2);
  74736. tmat2.m[12] = x;
  74737. tmat2.m[13] = y;
  74738. tmat2.m[14] = z;
  74739. tmat2.multiplyToRef(tmat, tmat);
  74740. }
  74741. if (parentBone) {
  74742. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74743. }
  74744. tmat.multiplyToRef(meshMat, tmat);
  74745. position.x = tmat.m[12];
  74746. position.y = tmat.m[13];
  74747. position.z = tmat.m[14];
  74748. };
  74749. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74750. var len = bones.length;
  74751. var meshPos = this.mesh.position;
  74752. for (var i = 0; i < len; i++) {
  74753. var bone = bones[i];
  74754. var points = this._debugLines[i];
  74755. if (!points) {
  74756. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74757. this._debugLines[i] = points;
  74758. }
  74759. this._getBonePosition(points[0], bone, meshMat);
  74760. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  74761. points[0].subtractInPlace(meshPos);
  74762. points[1].subtractInPlace(meshPos);
  74763. }
  74764. };
  74765. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  74766. var len = bones.length;
  74767. var boneNum = 0;
  74768. var meshPos = this.mesh.position;
  74769. for (var i = len - 1; i >= 0; i--) {
  74770. var childBone = bones[i];
  74771. var parentBone = childBone.getParent();
  74772. if (!parentBone) {
  74773. continue;
  74774. }
  74775. var points = this._debugLines[boneNum];
  74776. if (!points) {
  74777. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74778. this._debugLines[boneNum] = points;
  74779. }
  74780. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  74781. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  74782. points[0].subtractInPlace(meshPos);
  74783. points[1].subtractInPlace(meshPos);
  74784. boneNum++;
  74785. }
  74786. };
  74787. SkeletonViewer.prototype.update = function () {
  74788. if (this.autoUpdateBonesMatrices) {
  74789. this.skeleton.computeAbsoluteTransforms();
  74790. }
  74791. if (this.skeleton.bones[0].length === undefined) {
  74792. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74793. }
  74794. else {
  74795. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74796. }
  74797. if (!this._debugMesh) {
  74798. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  74799. this._debugMesh.renderingGroupId = this.renderingGroupId;
  74800. }
  74801. else {
  74802. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  74803. }
  74804. this._debugMesh.position.copyFrom(this.mesh.position);
  74805. this._debugMesh.color = this.color;
  74806. };
  74807. SkeletonViewer.prototype.dispose = function () {
  74808. if (this._debugMesh) {
  74809. this.isEnabled = false;
  74810. this._debugMesh.dispose();
  74811. this._debugMesh = null;
  74812. }
  74813. };
  74814. return SkeletonViewer;
  74815. }());
  74816. return Debug;
  74817. }());
  74818. BABYLON.Debug = Debug;
  74819. })(BABYLON || (BABYLON = {}));
  74820. //# sourceMappingURL=babylon.debugModules.js.map
  74821. var BABYLON;
  74822. (function (BABYLON) {
  74823. var RayHelper = /** @class */ (function () {
  74824. function RayHelper(ray) {
  74825. this.ray = ray;
  74826. }
  74827. RayHelper.CreateAndShow = function (ray, scene, color) {
  74828. var helper = new RayHelper(ray);
  74829. helper.show(scene, color);
  74830. return helper;
  74831. };
  74832. RayHelper.prototype.show = function (scene, color) {
  74833. if (!this._renderFunction && this.ray) {
  74834. var ray = this.ray;
  74835. this._renderFunction = this._render.bind(this);
  74836. this._scene = scene;
  74837. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  74838. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  74839. if (this._renderFunction) {
  74840. this._scene.registerBeforeRender(this._renderFunction);
  74841. }
  74842. }
  74843. if (color && this._renderLine) {
  74844. this._renderLine.color.copyFrom(color);
  74845. }
  74846. };
  74847. RayHelper.prototype.hide = function () {
  74848. if (this._renderFunction && this._scene) {
  74849. this._scene.unregisterBeforeRender(this._renderFunction);
  74850. this._scene = null;
  74851. this._renderFunction = null;
  74852. if (this._renderLine) {
  74853. this._renderLine.dispose();
  74854. this._renderLine = null;
  74855. }
  74856. this._renderPoints = [];
  74857. }
  74858. };
  74859. RayHelper.prototype._render = function () {
  74860. var ray = this.ray;
  74861. if (!ray) {
  74862. return;
  74863. }
  74864. var point = this._renderPoints[1];
  74865. var len = Math.min(ray.length, 1000000);
  74866. point.copyFrom(ray.direction);
  74867. point.scaleInPlace(len);
  74868. point.addInPlace(ray.origin);
  74869. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  74870. };
  74871. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  74872. this._attachedToMesh = mesh;
  74873. var ray = this.ray;
  74874. if (!ray) {
  74875. return;
  74876. }
  74877. if (!ray.direction) {
  74878. ray.direction = BABYLON.Vector3.Zero();
  74879. }
  74880. if (!ray.origin) {
  74881. ray.origin = BABYLON.Vector3.Zero();
  74882. }
  74883. if (length) {
  74884. ray.length = length;
  74885. }
  74886. if (!meshSpaceOrigin) {
  74887. meshSpaceOrigin = BABYLON.Vector3.Zero();
  74888. }
  74889. if (!meshSpaceDirection) {
  74890. // -1 so that this will work with Mesh.lookAt
  74891. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  74892. }
  74893. if (!this._meshSpaceDirection) {
  74894. this._meshSpaceDirection = meshSpaceDirection.clone();
  74895. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  74896. }
  74897. else {
  74898. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  74899. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  74900. }
  74901. if (!this._updateToMeshFunction) {
  74902. this._updateToMeshFunction = this._updateToMesh.bind(this);
  74903. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  74904. }
  74905. this._updateToMesh();
  74906. };
  74907. RayHelper.prototype.detachFromMesh = function () {
  74908. if (this._attachedToMesh) {
  74909. if (this._updateToMeshFunction) {
  74910. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  74911. }
  74912. this._attachedToMesh = null;
  74913. this._updateToMeshFunction = null;
  74914. }
  74915. };
  74916. RayHelper.prototype._updateToMesh = function () {
  74917. var ray = this.ray;
  74918. if (!this._attachedToMesh || !ray) {
  74919. return;
  74920. }
  74921. if (this._attachedToMesh._isDisposed) {
  74922. this.detachFromMesh();
  74923. return;
  74924. }
  74925. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  74926. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  74927. };
  74928. RayHelper.prototype.dispose = function () {
  74929. this.hide();
  74930. this.detachFromMesh();
  74931. this.ray = null;
  74932. };
  74933. return RayHelper;
  74934. }());
  74935. BABYLON.RayHelper = RayHelper;
  74936. })(BABYLON || (BABYLON = {}));
  74937. //# sourceMappingURL=babylon.rayHelper.js.map
  74938. var BABYLON;
  74939. (function (BABYLON) {
  74940. // load the inspector using require, if not present in the global namespace.
  74941. var DebugLayer = /** @class */ (function () {
  74942. function DebugLayer(scene) {
  74943. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74944. this._scene = scene;
  74945. // load inspector using require, if it doesn't exist on the global namespace.
  74946. }
  74947. /** Creates the inspector window. */
  74948. DebugLayer.prototype._createInspector = function (config) {
  74949. if (config === void 0) { config = {}; }
  74950. var popup = config.popup || false;
  74951. var initialTab = config.initialTab || 0;
  74952. var parentElement = config.parentElement || null;
  74953. if (!this._inspector) {
  74954. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74955. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  74956. } // else nothing to do,; instance is already existing
  74957. };
  74958. DebugLayer.prototype.isVisible = function () {
  74959. if (!this._inspector) {
  74960. return false;
  74961. }
  74962. return true;
  74963. };
  74964. DebugLayer.prototype.hide = function () {
  74965. if (this._inspector) {
  74966. try {
  74967. this._inspector.dispose();
  74968. }
  74969. catch (e) {
  74970. // If the inspector has been removed directly from the inspector tool
  74971. }
  74972. this._inspector = null;
  74973. }
  74974. };
  74975. DebugLayer.prototype.show = function (config) {
  74976. if (config === void 0) { config = {}; }
  74977. if (typeof this.BJSINSPECTOR == 'undefined') {
  74978. // Load inspector and add it to the DOM
  74979. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  74980. }
  74981. else {
  74982. // Otherwise creates the inspector
  74983. this._createInspector(config);
  74984. }
  74985. };
  74986. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  74987. return DebugLayer;
  74988. }());
  74989. BABYLON.DebugLayer = DebugLayer;
  74990. })(BABYLON || (BABYLON = {}));
  74991. //# sourceMappingURL=babylon.debugLayer.js.map
  74992. var BABYLON;
  74993. (function (BABYLON) {
  74994. var BoundingBoxRenderer = /** @class */ (function () {
  74995. function BoundingBoxRenderer(scene) {
  74996. this.frontColor = new BABYLON.Color3(1, 1, 1);
  74997. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  74998. this.showBackLines = true;
  74999. this.renderList = new BABYLON.SmartArray(32);
  75000. this._vertexBuffers = {};
  75001. this._scene = scene;
  75002. }
  75003. BoundingBoxRenderer.prototype._prepareRessources = function () {
  75004. if (this._colorShader) {
  75005. return;
  75006. }
  75007. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  75008. attributes: [BABYLON.VertexBuffer.PositionKind],
  75009. uniforms: ["world", "viewProjection", "color"]
  75010. });
  75011. var engine = this._scene.getEngine();
  75012. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  75013. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  75014. this._createIndexBuffer();
  75015. };
  75016. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  75017. var engine = this._scene.getEngine();
  75018. 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]);
  75019. };
  75020. BoundingBoxRenderer.prototype._rebuild = function () {
  75021. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75022. if (vb) {
  75023. vb._rebuild();
  75024. }
  75025. this._createIndexBuffer();
  75026. };
  75027. BoundingBoxRenderer.prototype.reset = function () {
  75028. this.renderList.reset();
  75029. };
  75030. BoundingBoxRenderer.prototype.render = function () {
  75031. if (this.renderList.length === 0) {
  75032. return;
  75033. }
  75034. this._prepareRessources();
  75035. if (!this._colorShader.isReady()) {
  75036. return;
  75037. }
  75038. var engine = this._scene.getEngine();
  75039. engine.setDepthWrite(false);
  75040. this._colorShader._preBind();
  75041. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  75042. var boundingBox = this.renderList.data[boundingBoxIndex];
  75043. var min = boundingBox.minimum;
  75044. var max = boundingBox.maximum;
  75045. var diff = max.subtract(min);
  75046. var median = min.add(diff.scale(0.5));
  75047. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  75048. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  75049. .multiply(boundingBox.getWorldMatrix());
  75050. // VBOs
  75051. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  75052. if (this.showBackLines) {
  75053. // Back
  75054. engine.setDepthFunctionToGreaterOrEqual();
  75055. this._scene.resetCachedMaterial();
  75056. this._colorShader.setColor4("color", this.backColor.toColor4());
  75057. this._colorShader.bind(worldMatrix);
  75058. // Draw order
  75059. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75060. }
  75061. // Front
  75062. engine.setDepthFunctionToLess();
  75063. this._scene.resetCachedMaterial();
  75064. this._colorShader.setColor4("color", this.frontColor.toColor4());
  75065. this._colorShader.bind(worldMatrix);
  75066. // Draw order
  75067. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75068. }
  75069. this._colorShader.unbind();
  75070. engine.setDepthFunctionToLessOrEqual();
  75071. engine.setDepthWrite(true);
  75072. };
  75073. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  75074. this._prepareRessources();
  75075. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  75076. return;
  75077. }
  75078. var engine = this._scene.getEngine();
  75079. engine.setDepthWrite(false);
  75080. engine.setColorWrite(false);
  75081. this._colorShader._preBind();
  75082. var boundingBox = mesh._boundingInfo.boundingBox;
  75083. var min = boundingBox.minimum;
  75084. var max = boundingBox.maximum;
  75085. var diff = max.subtract(min);
  75086. var median = min.add(diff.scale(0.5));
  75087. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  75088. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  75089. .multiply(boundingBox.getWorldMatrix());
  75090. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  75091. engine.setDepthFunctionToLess();
  75092. this._scene.resetCachedMaterial();
  75093. this._colorShader.bind(worldMatrix);
  75094. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75095. this._colorShader.unbind();
  75096. engine.setDepthFunctionToLessOrEqual();
  75097. engine.setDepthWrite(true);
  75098. engine.setColorWrite(true);
  75099. };
  75100. BoundingBoxRenderer.prototype.dispose = function () {
  75101. if (!this._colorShader) {
  75102. return;
  75103. }
  75104. this.renderList.dispose();
  75105. this._colorShader.dispose();
  75106. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75107. if (buffer) {
  75108. buffer.dispose();
  75109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75110. }
  75111. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75112. };
  75113. return BoundingBoxRenderer;
  75114. }());
  75115. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  75116. })(BABYLON || (BABYLON = {}));
  75117. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  75118. var BABYLON;
  75119. (function (BABYLON) {
  75120. var MorphTarget = /** @class */ (function () {
  75121. function MorphTarget(name, influence) {
  75122. if (influence === void 0) { influence = 0; }
  75123. this.name = name;
  75124. this.animations = new Array();
  75125. this._positions = null;
  75126. this._normals = null;
  75127. this._tangents = null;
  75128. this.onInfluenceChanged = new BABYLON.Observable();
  75129. this.influence = influence;
  75130. }
  75131. Object.defineProperty(MorphTarget.prototype, "influence", {
  75132. get: function () {
  75133. return this._influence;
  75134. },
  75135. set: function (influence) {
  75136. if (this._influence === influence) {
  75137. return;
  75138. }
  75139. var previous = this._influence;
  75140. this._influence = influence;
  75141. if (this.onInfluenceChanged.hasObservers) {
  75142. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  75143. }
  75144. },
  75145. enumerable: true,
  75146. configurable: true
  75147. });
  75148. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  75149. get: function () {
  75150. return !!this._positions;
  75151. },
  75152. enumerable: true,
  75153. configurable: true
  75154. });
  75155. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  75156. get: function () {
  75157. return !!this._normals;
  75158. },
  75159. enumerable: true,
  75160. configurable: true
  75161. });
  75162. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  75163. get: function () {
  75164. return !!this._tangents;
  75165. },
  75166. enumerable: true,
  75167. configurable: true
  75168. });
  75169. MorphTarget.prototype.setPositions = function (data) {
  75170. this._positions = data;
  75171. };
  75172. MorphTarget.prototype.getPositions = function () {
  75173. return this._positions;
  75174. };
  75175. MorphTarget.prototype.setNormals = function (data) {
  75176. this._normals = data;
  75177. };
  75178. MorphTarget.prototype.getNormals = function () {
  75179. return this._normals;
  75180. };
  75181. MorphTarget.prototype.setTangents = function (data) {
  75182. this._tangents = data;
  75183. };
  75184. MorphTarget.prototype.getTangents = function () {
  75185. return this._tangents;
  75186. };
  75187. /**
  75188. * Serializes the current target into a Serialization object.
  75189. * Returns the serialized object.
  75190. */
  75191. MorphTarget.prototype.serialize = function () {
  75192. var serializationObject = {};
  75193. serializationObject.name = this.name;
  75194. serializationObject.influence = this.influence;
  75195. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  75196. if (this.hasNormals) {
  75197. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  75198. }
  75199. if (this.hasTangents) {
  75200. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  75201. }
  75202. // Animations
  75203. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  75204. return serializationObject;
  75205. };
  75206. // Statics
  75207. MorphTarget.Parse = function (serializationObject) {
  75208. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  75209. result.setPositions(serializationObject.positions);
  75210. if (serializationObject.normals) {
  75211. result.setNormals(serializationObject.normals);
  75212. }
  75213. if (serializationObject.tangents) {
  75214. result.setTangents(serializationObject.tangents);
  75215. }
  75216. // Animations
  75217. if (serializationObject.animations) {
  75218. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  75219. var parsedAnimation = serializationObject.animations[animationIndex];
  75220. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  75221. }
  75222. }
  75223. return result;
  75224. };
  75225. MorphTarget.FromMesh = function (mesh, name, influence) {
  75226. if (!name) {
  75227. name = mesh.name;
  75228. }
  75229. var result = new MorphTarget(name, influence);
  75230. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75232. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  75233. }
  75234. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  75235. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  75236. }
  75237. return result;
  75238. };
  75239. return MorphTarget;
  75240. }());
  75241. BABYLON.MorphTarget = MorphTarget;
  75242. })(BABYLON || (BABYLON = {}));
  75243. //# sourceMappingURL=babylon.morphTarget.js.map
  75244. var BABYLON;
  75245. (function (BABYLON) {
  75246. var MorphTargetManager = /** @class */ (function () {
  75247. function MorphTargetManager(scene) {
  75248. if (scene === void 0) { scene = null; }
  75249. this._targets = new Array();
  75250. this._targetObservable = new Array();
  75251. this._activeTargets = new BABYLON.SmartArray(16);
  75252. this._supportsNormals = false;
  75253. this._supportsTangents = false;
  75254. this._vertexCount = 0;
  75255. this._uniqueId = 0;
  75256. this._tempInfluences = new Array();
  75257. if (!scene) {
  75258. scene = BABYLON.Engine.LastCreatedScene;
  75259. }
  75260. this._scene = scene;
  75261. if (this._scene) {
  75262. this._scene.morphTargetManagers.push(this);
  75263. this._uniqueId = this._scene.getUniqueId();
  75264. }
  75265. }
  75266. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  75267. get: function () {
  75268. return this._uniqueId;
  75269. },
  75270. enumerable: true,
  75271. configurable: true
  75272. });
  75273. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  75274. get: function () {
  75275. return this._vertexCount;
  75276. },
  75277. enumerable: true,
  75278. configurable: true
  75279. });
  75280. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  75281. get: function () {
  75282. return this._supportsNormals;
  75283. },
  75284. enumerable: true,
  75285. configurable: true
  75286. });
  75287. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  75288. get: function () {
  75289. return this._supportsTangents;
  75290. },
  75291. enumerable: true,
  75292. configurable: true
  75293. });
  75294. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  75295. get: function () {
  75296. return this._targets.length;
  75297. },
  75298. enumerable: true,
  75299. configurable: true
  75300. });
  75301. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  75302. get: function () {
  75303. return this._activeTargets.length;
  75304. },
  75305. enumerable: true,
  75306. configurable: true
  75307. });
  75308. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  75309. get: function () {
  75310. return this._influences;
  75311. },
  75312. enumerable: true,
  75313. configurable: true
  75314. });
  75315. MorphTargetManager.prototype.getActiveTarget = function (index) {
  75316. return this._activeTargets.data[index];
  75317. };
  75318. MorphTargetManager.prototype.getTarget = function (index) {
  75319. return this._targets[index];
  75320. };
  75321. MorphTargetManager.prototype.addTarget = function (target) {
  75322. var _this = this;
  75323. this._targets.push(target);
  75324. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  75325. _this._syncActiveTargets(needUpdate);
  75326. }));
  75327. this._syncActiveTargets(true);
  75328. };
  75329. MorphTargetManager.prototype.removeTarget = function (target) {
  75330. var index = this._targets.indexOf(target);
  75331. if (index >= 0) {
  75332. this._targets.splice(index, 1);
  75333. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  75334. this._syncActiveTargets(true);
  75335. }
  75336. };
  75337. /**
  75338. * Serializes the current manager into a Serialization object.
  75339. * Returns the serialized object.
  75340. */
  75341. MorphTargetManager.prototype.serialize = function () {
  75342. var serializationObject = {};
  75343. serializationObject.id = this.uniqueId;
  75344. serializationObject.targets = [];
  75345. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75346. var target = _a[_i];
  75347. serializationObject.targets.push(target.serialize());
  75348. }
  75349. return serializationObject;
  75350. };
  75351. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  75352. var influenceCount = 0;
  75353. this._activeTargets.reset();
  75354. this._supportsNormals = true;
  75355. this._supportsTangents = true;
  75356. this._vertexCount = 0;
  75357. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75358. var target = _a[_i];
  75359. this._activeTargets.push(target);
  75360. this._tempInfluences[influenceCount++] = target.influence;
  75361. var positions = target.getPositions();
  75362. if (positions) {
  75363. this._supportsNormals = this._supportsNormals && target.hasNormals;
  75364. this._supportsTangents = this._supportsTangents && target.hasTangents;
  75365. var vertexCount = positions.length / 3;
  75366. if (this._vertexCount === 0) {
  75367. this._vertexCount = vertexCount;
  75368. }
  75369. else if (this._vertexCount !== vertexCount) {
  75370. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  75371. return;
  75372. }
  75373. }
  75374. }
  75375. if (!this._influences || this._influences.length !== influenceCount) {
  75376. this._influences = new Float32Array(influenceCount);
  75377. }
  75378. for (var index = 0; index < influenceCount; index++) {
  75379. this._influences[index] = this._tempInfluences[index];
  75380. }
  75381. if (needUpdate && this._scene) {
  75382. // Flag meshes as dirty to resync with the active targets
  75383. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  75384. var mesh = _c[_b];
  75385. if (mesh.morphTargetManager === this) {
  75386. mesh._syncGeometryWithMorphTargetManager();
  75387. }
  75388. }
  75389. }
  75390. };
  75391. // Statics
  75392. MorphTargetManager.Parse = function (serializationObject, scene) {
  75393. var result = new MorphTargetManager(scene);
  75394. result._uniqueId = serializationObject.id;
  75395. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  75396. var targetData = _a[_i];
  75397. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  75398. }
  75399. return result;
  75400. };
  75401. return MorphTargetManager;
  75402. }());
  75403. BABYLON.MorphTargetManager = MorphTargetManager;
  75404. })(BABYLON || (BABYLON = {}));
  75405. //# sourceMappingURL=babylon.morphTargetManager.js.map
  75406. var BABYLON;
  75407. (function (BABYLON) {
  75408. var Octree = /** @class */ (function () {
  75409. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  75410. if (maxDepth === void 0) { maxDepth = 2; }
  75411. this.maxDepth = maxDepth;
  75412. this.dynamicContent = new Array();
  75413. this._maxBlockCapacity = maxBlockCapacity || 64;
  75414. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  75415. this._creationFunc = creationFunc;
  75416. }
  75417. // Methods
  75418. Octree.prototype.update = function (worldMin, worldMax, entries) {
  75419. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  75420. };
  75421. Octree.prototype.addMesh = function (entry) {
  75422. for (var index = 0; index < this.blocks.length; index++) {
  75423. var block = this.blocks[index];
  75424. block.addEntry(entry);
  75425. }
  75426. };
  75427. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  75428. this._selectionContent.reset();
  75429. for (var index = 0; index < this.blocks.length; index++) {
  75430. var block = this.blocks[index];
  75431. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  75432. }
  75433. if (allowDuplicate) {
  75434. this._selectionContent.concat(this.dynamicContent);
  75435. }
  75436. else {
  75437. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75438. }
  75439. return this._selectionContent;
  75440. };
  75441. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  75442. this._selectionContent.reset();
  75443. for (var index = 0; index < this.blocks.length; index++) {
  75444. var block = this.blocks[index];
  75445. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  75446. }
  75447. if (allowDuplicate) {
  75448. this._selectionContent.concat(this.dynamicContent);
  75449. }
  75450. else {
  75451. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75452. }
  75453. return this._selectionContent;
  75454. };
  75455. Octree.prototype.intersectsRay = function (ray) {
  75456. this._selectionContent.reset();
  75457. for (var index = 0; index < this.blocks.length; index++) {
  75458. var block = this.blocks[index];
  75459. block.intersectsRay(ray, this._selectionContent);
  75460. }
  75461. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75462. return this._selectionContent;
  75463. };
  75464. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75465. target.blocks = new Array();
  75466. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75467. // Segmenting space
  75468. for (var x = 0; x < 2; x++) {
  75469. for (var y = 0; y < 2; y++) {
  75470. for (var z = 0; z < 2; z++) {
  75471. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75472. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75473. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75474. block.addEntries(entries);
  75475. target.blocks.push(block);
  75476. }
  75477. }
  75478. }
  75479. };
  75480. Octree.CreationFuncForMeshes = function (entry, block) {
  75481. var boundingInfo = entry.getBoundingInfo();
  75482. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75483. block.entries.push(entry);
  75484. }
  75485. };
  75486. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75487. var boundingInfo = entry.getBoundingInfo();
  75488. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75489. block.entries.push(entry);
  75490. }
  75491. };
  75492. return Octree;
  75493. }());
  75494. BABYLON.Octree = Octree;
  75495. })(BABYLON || (BABYLON = {}));
  75496. //# sourceMappingURL=babylon.octree.js.map
  75497. var BABYLON;
  75498. (function (BABYLON) {
  75499. var OctreeBlock = /** @class */ (function () {
  75500. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75501. this.entries = new Array();
  75502. this._boundingVectors = new Array();
  75503. this._capacity = capacity;
  75504. this._depth = depth;
  75505. this._maxDepth = maxDepth;
  75506. this._creationFunc = creationFunc;
  75507. this._minPoint = minPoint;
  75508. this._maxPoint = maxPoint;
  75509. this._boundingVectors.push(minPoint.clone());
  75510. this._boundingVectors.push(maxPoint.clone());
  75511. this._boundingVectors.push(minPoint.clone());
  75512. this._boundingVectors[2].x = maxPoint.x;
  75513. this._boundingVectors.push(minPoint.clone());
  75514. this._boundingVectors[3].y = maxPoint.y;
  75515. this._boundingVectors.push(minPoint.clone());
  75516. this._boundingVectors[4].z = maxPoint.z;
  75517. this._boundingVectors.push(maxPoint.clone());
  75518. this._boundingVectors[5].z = minPoint.z;
  75519. this._boundingVectors.push(maxPoint.clone());
  75520. this._boundingVectors[6].x = minPoint.x;
  75521. this._boundingVectors.push(maxPoint.clone());
  75522. this._boundingVectors[7].y = minPoint.y;
  75523. }
  75524. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75525. // Property
  75526. get: function () {
  75527. return this._capacity;
  75528. },
  75529. enumerable: true,
  75530. configurable: true
  75531. });
  75532. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75533. get: function () {
  75534. return this._minPoint;
  75535. },
  75536. enumerable: true,
  75537. configurable: true
  75538. });
  75539. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75540. get: function () {
  75541. return this._maxPoint;
  75542. },
  75543. enumerable: true,
  75544. configurable: true
  75545. });
  75546. // Methods
  75547. OctreeBlock.prototype.addEntry = function (entry) {
  75548. if (this.blocks) {
  75549. for (var index = 0; index < this.blocks.length; index++) {
  75550. var block = this.blocks[index];
  75551. block.addEntry(entry);
  75552. }
  75553. return;
  75554. }
  75555. this._creationFunc(entry, this);
  75556. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75557. this.createInnerBlocks();
  75558. }
  75559. };
  75560. OctreeBlock.prototype.addEntries = function (entries) {
  75561. for (var index = 0; index < entries.length; index++) {
  75562. var mesh = entries[index];
  75563. this.addEntry(mesh);
  75564. }
  75565. };
  75566. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75567. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75568. if (this.blocks) {
  75569. for (var index = 0; index < this.blocks.length; index++) {
  75570. var block = this.blocks[index];
  75571. block.select(frustumPlanes, selection, allowDuplicate);
  75572. }
  75573. return;
  75574. }
  75575. if (allowDuplicate) {
  75576. selection.concat(this.entries);
  75577. }
  75578. else {
  75579. selection.concatWithNoDuplicate(this.entries);
  75580. }
  75581. }
  75582. };
  75583. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75584. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75585. if (this.blocks) {
  75586. for (var index = 0; index < this.blocks.length; index++) {
  75587. var block = this.blocks[index];
  75588. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75589. }
  75590. return;
  75591. }
  75592. if (allowDuplicate) {
  75593. selection.concat(this.entries);
  75594. }
  75595. else {
  75596. selection.concatWithNoDuplicate(this.entries);
  75597. }
  75598. }
  75599. };
  75600. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75601. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75602. if (this.blocks) {
  75603. for (var index = 0; index < this.blocks.length; index++) {
  75604. var block = this.blocks[index];
  75605. block.intersectsRay(ray, selection);
  75606. }
  75607. return;
  75608. }
  75609. selection.concatWithNoDuplicate(this.entries);
  75610. }
  75611. };
  75612. OctreeBlock.prototype.createInnerBlocks = function () {
  75613. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75614. };
  75615. return OctreeBlock;
  75616. }());
  75617. BABYLON.OctreeBlock = OctreeBlock;
  75618. })(BABYLON || (BABYLON = {}));
  75619. //# sourceMappingURL=babylon.octreeBlock.js.map
  75620. var BABYLON;
  75621. (function (BABYLON) {
  75622. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75623. __extends(VRDistortionCorrectionPostProcess, _super);
  75624. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75625. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75626. 'LensCenter',
  75627. 'Scale',
  75628. 'ScaleIn',
  75629. 'HmdWarpParam'
  75630. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75631. _this._isRightEye = isRightEye;
  75632. _this._distortionFactors = vrMetrics.distortionK;
  75633. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75634. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75635. _this.adaptScaleToCurrentViewport = true;
  75636. _this.onSizeChangedObservable.add(function () {
  75637. _this.aspectRatio = _this.width * .5 / _this.height;
  75638. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75639. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75640. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75641. });
  75642. _this.onApplyObservable.add(function (effect) {
  75643. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75644. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75645. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75646. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75647. });
  75648. return _this;
  75649. }
  75650. return VRDistortionCorrectionPostProcess;
  75651. }(BABYLON.PostProcess));
  75652. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75653. })(BABYLON || (BABYLON = {}));
  75654. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75655. var BABYLON;
  75656. (function (BABYLON) {
  75657. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75658. __extends(AnaglyphPostProcess, _super);
  75659. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75660. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75661. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75662. _this.onApplyObservable.add(function (effect) {
  75663. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75664. });
  75665. return _this;
  75666. }
  75667. return AnaglyphPostProcess;
  75668. }(BABYLON.PostProcess));
  75669. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75670. })(BABYLON || (BABYLON = {}));
  75671. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75672. var BABYLON;
  75673. (function (BABYLON) {
  75674. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75675. __extends(StereoscopicInterlacePostProcess, _super);
  75676. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75677. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75678. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75679. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75680. _this.onSizeChangedObservable.add(function () {
  75681. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75682. });
  75683. _this.onApplyObservable.add(function (effect) {
  75684. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75685. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75686. });
  75687. return _this;
  75688. }
  75689. return StereoscopicInterlacePostProcess;
  75690. }(BABYLON.PostProcess));
  75691. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75692. })(BABYLON || (BABYLON = {}));
  75693. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75694. var BABYLON;
  75695. (function (BABYLON) {
  75696. /**
  75697. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75698. * Screen rotation is taken into account.
  75699. */
  75700. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75701. function FreeCameraDeviceOrientationInput() {
  75702. var _this = this;
  75703. this._screenOrientationAngle = 0;
  75704. this._screenQuaternion = new BABYLON.Quaternion();
  75705. this._alpha = 0;
  75706. this._beta = 0;
  75707. this._gamma = 0;
  75708. this._orientationChanged = function () {
  75709. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75710. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75711. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75712. };
  75713. this._deviceOrientation = function (evt) {
  75714. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75715. _this._beta = evt.beta !== null ? evt.beta : 0;
  75716. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75717. };
  75718. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75719. this._orientationChanged();
  75720. }
  75721. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75722. get: function () {
  75723. return this._camera;
  75724. },
  75725. set: function (camera) {
  75726. this._camera = camera;
  75727. if (this._camera != null && !this._camera.rotationQuaternion) {
  75728. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75729. }
  75730. },
  75731. enumerable: true,
  75732. configurable: true
  75733. });
  75734. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75735. window.addEventListener("orientationchange", this._orientationChanged);
  75736. window.addEventListener("deviceorientation", this._deviceOrientation);
  75737. //In certain cases, the attach control is called AFTER orientation was changed,
  75738. //So this is needed.
  75739. this._orientationChanged();
  75740. };
  75741. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75742. window.removeEventListener("orientationchange", this._orientationChanged);
  75743. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75744. };
  75745. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75746. //if no device orientation provided, don't update the rotation.
  75747. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75748. if (!this._alpha)
  75749. return;
  75750. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75751. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75752. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75753. //Mirror on XY Plane
  75754. this._camera.rotationQuaternion.z *= -1;
  75755. this._camera.rotationQuaternion.w *= -1;
  75756. };
  75757. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75758. return "FreeCameraDeviceOrientationInput";
  75759. };
  75760. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  75761. return "deviceOrientation";
  75762. };
  75763. return FreeCameraDeviceOrientationInput;
  75764. }());
  75765. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  75766. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  75767. })(BABYLON || (BABYLON = {}));
  75768. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  75769. var BABYLON;
  75770. (function (BABYLON) {
  75771. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  75772. function ArcRotateCameraVRDeviceOrientationInput() {
  75773. this.alphaCorrection = 1;
  75774. this.betaCorrection = 1;
  75775. this.gammaCorrection = 1;
  75776. this._alpha = 0;
  75777. this._gamma = 0;
  75778. this._dirty = false;
  75779. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  75780. }
  75781. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75782. this.camera.attachControl(element, noPreventDefault);
  75783. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  75784. };
  75785. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  75786. if (evt.alpha !== null) {
  75787. this._alpha = +evt.alpha | 0;
  75788. }
  75789. if (evt.gamma !== null) {
  75790. this._gamma = +evt.gamma | 0;
  75791. }
  75792. this._dirty = true;
  75793. };
  75794. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  75795. if (this._dirty) {
  75796. this._dirty = false;
  75797. if (this._gamma < 0) {
  75798. this._gamma = 180 + this._gamma;
  75799. }
  75800. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  75801. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  75802. }
  75803. };
  75804. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  75805. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  75806. };
  75807. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  75808. return "ArcRotateCameraVRDeviceOrientationInput";
  75809. };
  75810. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  75811. return "VRDeviceOrientation";
  75812. };
  75813. return ArcRotateCameraVRDeviceOrientationInput;
  75814. }());
  75815. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  75816. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  75817. })(BABYLON || (BABYLON = {}));
  75818. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  75819. var BABYLON;
  75820. (function (BABYLON) {
  75821. var VRCameraMetrics = /** @class */ (function () {
  75822. function VRCameraMetrics() {
  75823. this.compensateDistortion = true;
  75824. }
  75825. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  75826. get: function () {
  75827. return this.hResolution / (2 * this.vResolution);
  75828. },
  75829. enumerable: true,
  75830. configurable: true
  75831. });
  75832. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  75833. get: function () {
  75834. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  75835. },
  75836. enumerable: true,
  75837. configurable: true
  75838. });
  75839. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  75840. get: function () {
  75841. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75842. var h = (4 * meters) / this.hScreenSize;
  75843. return BABYLON.Matrix.Translation(h, 0, 0);
  75844. },
  75845. enumerable: true,
  75846. configurable: true
  75847. });
  75848. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  75849. get: function () {
  75850. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75851. var h = (4 * meters) / this.hScreenSize;
  75852. return BABYLON.Matrix.Translation(-h, 0, 0);
  75853. },
  75854. enumerable: true,
  75855. configurable: true
  75856. });
  75857. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  75858. get: function () {
  75859. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  75860. },
  75861. enumerable: true,
  75862. configurable: true
  75863. });
  75864. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  75865. get: function () {
  75866. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  75867. },
  75868. enumerable: true,
  75869. configurable: true
  75870. });
  75871. VRCameraMetrics.GetDefault = function () {
  75872. var result = new VRCameraMetrics();
  75873. result.hResolution = 1280;
  75874. result.vResolution = 800;
  75875. result.hScreenSize = 0.149759993;
  75876. result.vScreenSize = 0.0935999975;
  75877. result.vScreenCenter = 0.0467999987;
  75878. result.eyeToScreenDistance = 0.0410000011;
  75879. result.lensSeparationDistance = 0.0635000020;
  75880. result.interpupillaryDistance = 0.0640000030;
  75881. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  75882. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  75883. result.postProcessScaleFactor = 1.714605507808412;
  75884. result.lensCenterOffset = 0.151976421;
  75885. return result;
  75886. };
  75887. return VRCameraMetrics;
  75888. }());
  75889. BABYLON.VRCameraMetrics = VRCameraMetrics;
  75890. })(BABYLON || (BABYLON = {}));
  75891. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  75892. var BABYLON;
  75893. (function (BABYLON) {
  75894. /**
  75895. * This represents a WebVR camera.
  75896. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  75897. * @example http://doc.babylonjs.com/how_to/webvr_camera
  75898. */
  75899. var WebVRFreeCamera = /** @class */ (function (_super) {
  75900. __extends(WebVRFreeCamera, _super);
  75901. /**
  75902. * Instantiates a WebVRFreeCamera.
  75903. * @param name The name of the WebVRFreeCamera
  75904. * @param position The starting anchor position for the camera
  75905. * @param scene The scene the camera belongs to
  75906. * @param webVROptions a set of customizable options for the webVRCamera
  75907. */
  75908. function WebVRFreeCamera(name, position, scene, webVROptions) {
  75909. if (webVROptions === void 0) { webVROptions = {}; }
  75910. var _this = _super.call(this, name, position, scene) || this;
  75911. _this.webVROptions = webVROptions;
  75912. /**
  75913. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  75914. */
  75915. _this._vrDevice = null;
  75916. /**
  75917. * The rawPose of the vrDevice.
  75918. */
  75919. _this.rawPose = null;
  75920. _this._specsVersion = "1.1";
  75921. _this._attached = false;
  75922. _this._descendants = [];
  75923. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75924. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75925. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  75926. _this._standingMatrix = null;
  75927. /**
  75928. * Represents device position in babylon space.
  75929. */
  75930. _this.devicePosition = BABYLON.Vector3.Zero();
  75931. /**
  75932. * Represents device rotation in babylon space.
  75933. */
  75934. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  75935. /**
  75936. * The scale of the device to be used when translating from device space to babylon space.
  75937. */
  75938. _this.deviceScaleFactor = 1;
  75939. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75940. _this._worldToDevice = BABYLON.Matrix.Identity();
  75941. /**
  75942. * References to the webVR controllers for the vrDevice.
  75943. */
  75944. _this.controllers = [];
  75945. /**
  75946. * Emits an event when a controller is attached.
  75947. */
  75948. _this.onControllersAttachedObservable = new BABYLON.Observable();
  75949. /**
  75950. * Emits an event when a controller's mesh has been loaded;
  75951. */
  75952. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75953. /**
  75954. * If the rig cameras be used as parent instead of this camera.
  75955. */
  75956. _this.rigParenting = true;
  75957. _this._defaultHeight = undefined;
  75958. _this._workingVector = BABYLON.Vector3.Zero();
  75959. _this._oneVector = BABYLON.Vector3.One();
  75960. _this._workingMatrix = BABYLON.Matrix.Identity();
  75961. _this._cache.position = BABYLON.Vector3.Zero();
  75962. if (webVROptions.defaultHeight) {
  75963. _this._defaultHeight = webVROptions.defaultHeight;
  75964. _this.position.y = _this._defaultHeight;
  75965. }
  75966. _this.minZ = 0.1;
  75967. //legacy support - the compensation boolean was removed.
  75968. if (arguments.length === 5) {
  75969. _this.webVROptions = arguments[4];
  75970. }
  75971. // default webVR options
  75972. if (_this.webVROptions.trackPosition == undefined) {
  75973. _this.webVROptions.trackPosition = true;
  75974. }
  75975. if (_this.webVROptions.controllerMeshes == undefined) {
  75976. _this.webVROptions.controllerMeshes = true;
  75977. }
  75978. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  75979. _this.webVROptions.defaultLightingOnControllers = true;
  75980. }
  75981. _this.rotationQuaternion = new BABYLON.Quaternion();
  75982. if (_this.webVROptions && _this.webVROptions.positionScale) {
  75983. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  75984. }
  75985. //enable VR
  75986. var engine = _this.getEngine();
  75987. _this._onVREnabled = function (success) { if (success) {
  75988. _this.initControllers();
  75989. } };
  75990. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  75991. engine.initWebVR().add(function (event) {
  75992. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  75993. return;
  75994. }
  75995. _this._vrDevice = event.vrDisplay;
  75996. //reset the rig parameters.
  75997. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  75998. if (_this._attached) {
  75999. _this.getEngine().enableVR();
  76000. }
  76001. });
  76002. if (typeof (VRFrameData) !== "undefined")
  76003. _this._frameData = new VRFrameData();
  76004. /**
  76005. * The idea behind the following lines:
  76006. * objects that have the camera as parent should actually have the rig cameras as a parent.
  76007. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  76008. * the second will not show it correctly.
  76009. *
  76010. * To solve this - each object that has the camera as parent will be added to a protected array.
  76011. * When the rig camera renders, it will take this array and set all of those to be its children.
  76012. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  76013. * Amazing!
  76014. */
  76015. scene.onBeforeCameraRenderObservable.add(function (camera) {
  76016. if (camera.parent === _this && _this.rigParenting) {
  76017. _this._descendants = _this.getDescendants(true, function (n) {
  76018. // don't take the cameras or the controllers!
  76019. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  76020. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  76021. return !isController && !isRigCamera;
  76022. });
  76023. _this._descendants.forEach(function (node) {
  76024. node.parent = camera;
  76025. });
  76026. }
  76027. });
  76028. scene.onAfterCameraRenderObservable.add(function (camera) {
  76029. if (camera.parent === _this && _this.rigParenting) {
  76030. _this._descendants.forEach(function (node) {
  76031. node.parent = _this;
  76032. });
  76033. }
  76034. });
  76035. return _this;
  76036. }
  76037. /**
  76038. * Gets the device distance from the ground.
  76039. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  76040. */
  76041. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  76042. if (this._standingMatrix && this._defaultHeight === undefined) {
  76043. // Add standing matrix offset to get real offset from ground in room
  76044. this._standingMatrix.getTranslationToRef(this._workingVector);
  76045. return this._deviceRoomPosition.y + this._workingVector.y;
  76046. }
  76047. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  76048. return this._defaultHeight || 0;
  76049. };
  76050. /**
  76051. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  76052. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  76053. */
  76054. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  76055. var _this = this;
  76056. if (callback === void 0) { callback = function (bool) { }; }
  76057. // Use standing matrix if available
  76058. if (!navigator || !navigator.getVRDisplays) {
  76059. callback(false);
  76060. }
  76061. else {
  76062. navigator.getVRDisplays().then(function (displays) {
  76063. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  76064. callback(false);
  76065. }
  76066. else {
  76067. _this._standingMatrix = new BABYLON.Matrix();
  76068. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  76069. if (!_this.getScene().useRightHandedSystem) {
  76070. [2, 6, 8, 9, 14].forEach(function (num) {
  76071. if (_this._standingMatrix) {
  76072. _this._standingMatrix.m[num] *= -1;
  76073. }
  76074. });
  76075. }
  76076. callback(true);
  76077. }
  76078. });
  76079. }
  76080. };
  76081. /**
  76082. * Disposes the camera
  76083. */
  76084. WebVRFreeCamera.prototype.dispose = function () {
  76085. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  76086. _super.prototype.dispose.call(this);
  76087. };
  76088. /**
  76089. * Gets a vrController by name.
  76090. * @param name The name of the controller to retreive
  76091. * @returns the controller matching the name specified or null if not found
  76092. */
  76093. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  76094. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  76095. var gp = _a[_i];
  76096. if (gp.hand === name) {
  76097. return gp;
  76098. }
  76099. }
  76100. return null;
  76101. };
  76102. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  76103. /**
  76104. * The controller corrisponding to the users left hand.
  76105. */
  76106. get: function () {
  76107. if (!this._leftController) {
  76108. this._leftController = this.getControllerByName("left");
  76109. }
  76110. return this._leftController;
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. ;
  76116. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  76117. /**
  76118. * The controller corrisponding to the users right hand.
  76119. */
  76120. get: function () {
  76121. if (!this._rightController) {
  76122. this._rightController = this.getControllerByName("right");
  76123. }
  76124. return this._rightController;
  76125. },
  76126. enumerable: true,
  76127. configurable: true
  76128. });
  76129. ;
  76130. /**
  76131. * Casts a ray forward from the vrCamera's gaze.
  76132. * @param length Length of the ray (default: 100)
  76133. * @returns the ray corrisponding to the gaze
  76134. */
  76135. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  76136. if (length === void 0) { length = 100; }
  76137. if (this.leftCamera) {
  76138. // Use left eye to avoid computation to compute center on every call
  76139. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  76140. }
  76141. else {
  76142. return _super.prototype.getForwardRay.call(this, length);
  76143. }
  76144. };
  76145. /**
  76146. * Updates the camera based on device's frame data
  76147. */
  76148. WebVRFreeCamera.prototype._checkInputs = function () {
  76149. if (this._vrDevice && this._vrDevice.isPresenting) {
  76150. this._vrDevice.getFrameData(this._frameData);
  76151. this.updateFromDevice(this._frameData.pose);
  76152. }
  76153. _super.prototype._checkInputs.call(this);
  76154. };
  76155. /**
  76156. * Updates the poseControlled values based on the input device pose.
  76157. * @param poseData Pose coming from the device
  76158. */
  76159. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  76160. if (poseData && poseData.orientation) {
  76161. this.rawPose = poseData;
  76162. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  76163. if (this.getScene().useRightHandedSystem) {
  76164. this._deviceRoomRotationQuaternion.z *= -1;
  76165. this._deviceRoomRotationQuaternion.w *= -1;
  76166. }
  76167. if (this.webVROptions.trackPosition && this.rawPose.position) {
  76168. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  76169. if (this.getScene().useRightHandedSystem) {
  76170. this._deviceRoomPosition.z *= -1;
  76171. }
  76172. }
  76173. }
  76174. };
  76175. /**
  76176. * WebVR's attach control will start broadcasting frames to the device.
  76177. * Note that in certain browsers (chrome for example) this function must be called
  76178. * within a user-interaction callback. Example:
  76179. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  76180. *
  76181. * @param element html element to attach the vrDevice to
  76182. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  76183. */
  76184. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  76185. _super.prototype.attachControl.call(this, element, noPreventDefault);
  76186. this._attached = true;
  76187. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  76188. if (this._vrDevice) {
  76189. this.getEngine().enableVR();
  76190. }
  76191. };
  76192. /**
  76193. * Detaches the camera from the html element and disables VR
  76194. *
  76195. * @param element html element to detach from
  76196. */
  76197. WebVRFreeCamera.prototype.detachControl = function (element) {
  76198. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76199. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76200. _super.prototype.detachControl.call(this, element);
  76201. this._attached = false;
  76202. this.getEngine().disableVR();
  76203. };
  76204. /**
  76205. * @returns the name of this class
  76206. */
  76207. WebVRFreeCamera.prototype.getClassName = function () {
  76208. return "WebVRFreeCamera";
  76209. };
  76210. /**
  76211. * Calls resetPose on the vrDisplay
  76212. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  76213. */
  76214. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  76215. //uses the vrDisplay's "resetPose()".
  76216. //pitch and roll won't be affected.
  76217. this._vrDevice.resetPose();
  76218. };
  76219. /**
  76220. * Updates the rig cameras (left and right eye)
  76221. */
  76222. WebVRFreeCamera.prototype._updateRigCameras = function () {
  76223. var camLeft = this._rigCameras[0];
  76224. var camRight = this._rigCameras[1];
  76225. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76226. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76227. camLeft.position.copyFrom(this._deviceRoomPosition);
  76228. camRight.position.copyFrom(this._deviceRoomPosition);
  76229. };
  76230. /**
  76231. * Updates the cached values of the camera
  76232. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  76233. */
  76234. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  76235. var _this = this;
  76236. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  76237. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  76238. if (!this.updateCacheCalled) {
  76239. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  76240. this.updateCacheCalled = true;
  76241. this.update();
  76242. }
  76243. // Set working vector to the device position in room space rotated by the new rotation
  76244. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  76245. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  76246. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  76247. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  76248. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  76249. // Add translation from anchor position
  76250. this._deviceToWorld.getTranslationToRef(this._workingVector);
  76251. this._workingVector.addInPlace(this.position);
  76252. this._workingVector.subtractInPlace(this._cache.position);
  76253. this._deviceToWorld.setTranslation(this._workingVector);
  76254. // Set an inverted matrix to be used when updating the camera
  76255. this._deviceToWorld.invertToRef(this._worldToDevice);
  76256. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  76257. this.controllers.forEach(function (controller) {
  76258. controller._deviceToWorld = _this._deviceToWorld;
  76259. controller.update();
  76260. });
  76261. }
  76262. if (!ignoreParentClass) {
  76263. _super.prototype._updateCache.call(this);
  76264. }
  76265. this.updateCacheCalled = false;
  76266. };
  76267. /**
  76268. * Updates the current device position and rotation in the babylon world
  76269. */
  76270. WebVRFreeCamera.prototype.update = function () {
  76271. // Get current device position in babylon world
  76272. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  76273. // Get current device rotation in babylon world
  76274. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  76275. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  76276. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  76277. _super.prototype.update.call(this);
  76278. };
  76279. /**
  76280. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  76281. * @returns an identity matrix
  76282. */
  76283. WebVRFreeCamera.prototype._getViewMatrix = function () {
  76284. return BABYLON.Matrix.Identity();
  76285. };
  76286. /**
  76287. * This function is called by the two RIG cameras.
  76288. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  76289. */
  76290. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  76291. var _this = this;
  76292. //WebVR 1.1
  76293. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  76294. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  76295. if (!this.getScene().useRightHandedSystem) {
  76296. [2, 6, 8, 9, 14].forEach(function (num) {
  76297. _this._webvrViewMatrix.m[num] *= -1;
  76298. });
  76299. }
  76300. // update the camera rotation matrix
  76301. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  76302. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  76303. // Computing target and final matrix
  76304. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  76305. var parentCamera = this._cameraRigParams["parentCamera"];
  76306. // should the view matrix be updated with scale and position offset?
  76307. if (parentCamera.deviceScaleFactor !== 1) {
  76308. this._webvrViewMatrix.invert();
  76309. // scale the position, if set
  76310. if (parentCamera.deviceScaleFactor) {
  76311. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  76312. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  76313. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  76314. }
  76315. this._webvrViewMatrix.invert();
  76316. }
  76317. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  76318. return this._webvrViewMatrix;
  76319. };
  76320. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  76321. var _this = this;
  76322. var parentCamera = this.parent;
  76323. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  76324. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  76325. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  76326. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  76327. //babylon compatible matrix
  76328. if (!this.getScene().useRightHandedSystem) {
  76329. [8, 9, 10, 11].forEach(function (num) {
  76330. _this._projectionMatrix.m[num] *= -1;
  76331. });
  76332. }
  76333. return this._projectionMatrix;
  76334. };
  76335. /**
  76336. * Initializes the controllers and their meshes
  76337. */
  76338. WebVRFreeCamera.prototype.initControllers = function () {
  76339. var _this = this;
  76340. this.controllers = [];
  76341. var manager = this.getScene().gamepadManager;
  76342. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76343. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76344. var webVrController = gamepad;
  76345. if (webVrController.defaultModel) {
  76346. webVrController.defaultModel.setEnabled(false);
  76347. }
  76348. if (webVrController.hand === "right") {
  76349. _this._rightController = null;
  76350. }
  76351. if (webVrController.hand === "left") {
  76352. _this._rightController = null;
  76353. }
  76354. var controllerIndex = _this.controllers.indexOf(webVrController);
  76355. if (controllerIndex !== -1) {
  76356. _this.controllers.splice(controllerIndex, 1);
  76357. }
  76358. }
  76359. });
  76360. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76361. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76362. var webVrController_1 = gamepad;
  76363. webVrController_1._deviceToWorld = _this._deviceToWorld;
  76364. if (_this.webVROptions.controllerMeshes) {
  76365. if (webVrController_1.defaultModel) {
  76366. webVrController_1.defaultModel.setEnabled(true);
  76367. }
  76368. else {
  76369. // Load the meshes
  76370. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  76371. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  76372. if (_this.webVROptions.defaultLightingOnControllers) {
  76373. if (!_this._lightOnControllers) {
  76374. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  76375. }
  76376. var activateLightOnSubMeshes_1 = function (mesh, light) {
  76377. var children = mesh.getChildren();
  76378. if (children.length !== 0) {
  76379. children.forEach(function (mesh) {
  76380. light.includedOnlyMeshes.push(mesh);
  76381. activateLightOnSubMeshes_1(mesh, light);
  76382. });
  76383. }
  76384. };
  76385. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  76386. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  76387. }
  76388. });
  76389. }
  76390. }
  76391. webVrController_1.attachToPoseControlledCamera(_this);
  76392. // since this is async - sanity check. Is the controller already stored?
  76393. if (_this.controllers.indexOf(webVrController_1) === -1) {
  76394. //add to the controllers array
  76395. _this.controllers.push(webVrController_1);
  76396. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  76397. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  76398. // So we're overriding setting left & right manually to be sure
  76399. var firstViveWandDetected = false;
  76400. for (var i = 0; i < _this.controllers.length; i++) {
  76401. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76402. if (!firstViveWandDetected) {
  76403. firstViveWandDetected = true;
  76404. _this.controllers[i].hand = "left";
  76405. }
  76406. else {
  76407. _this.controllers[i].hand = "right";
  76408. }
  76409. }
  76410. }
  76411. //did we find enough controllers? Great! let the developer know.
  76412. if (_this.controllers.length >= 2) {
  76413. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  76414. }
  76415. }
  76416. }
  76417. });
  76418. };
  76419. return WebVRFreeCamera;
  76420. }(BABYLON.FreeCamera));
  76421. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  76422. })(BABYLON || (BABYLON = {}));
  76423. //# sourceMappingURL=babylon.webVRCamera.js.map
  76424. var BABYLON;
  76425. (function (BABYLON) {
  76426. // We're mainly based on the logic defined into the FreeCamera code
  76427. /**
  76428. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  76429. * being tilted forward or back and left or right.
  76430. */
  76431. var DeviceOrientationCamera = /** @class */ (function (_super) {
  76432. __extends(DeviceOrientationCamera, _super);
  76433. /**
  76434. * Creates a new device orientation camera. @see DeviceOrientationCamera
  76435. * @param name The name of the camera
  76436. * @param position The start position camera
  76437. * @param scene The scene the camera belongs to
  76438. */
  76439. function DeviceOrientationCamera(name, position, scene) {
  76440. var _this = _super.call(this, name, position, scene) || this;
  76441. _this._quaternionCache = new BABYLON.Quaternion();
  76442. _this.inputs.addDeviceOrientation();
  76443. return _this;
  76444. }
  76445. /**
  76446. * Gets the current instance class name ("DeviceOrientationCamera").
  76447. * This helps avoiding instanceof at run time.
  76448. * @returns the class name
  76449. */
  76450. DeviceOrientationCamera.prototype.getClassName = function () {
  76451. return "DeviceOrientationCamera";
  76452. };
  76453. /**
  76454. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  76455. */
  76456. DeviceOrientationCamera.prototype._checkInputs = function () {
  76457. _super.prototype._checkInputs.call(this);
  76458. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76459. if (this._initialQuaternion) {
  76460. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76461. }
  76462. };
  76463. /**
  76464. * Reset the camera to its default orientation on the specified axis only.
  76465. * @param axis The axis to reset
  76466. */
  76467. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76468. var _this = this;
  76469. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76470. //can only work if this camera has a rotation quaternion already.
  76471. if (!this.rotationQuaternion)
  76472. return;
  76473. if (!this._initialQuaternion) {
  76474. this._initialQuaternion = new BABYLON.Quaternion();
  76475. }
  76476. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76477. ['x', 'y', 'z'].forEach(function (axisName) {
  76478. if (!axis[axisName]) {
  76479. _this._initialQuaternion[axisName] = 0;
  76480. }
  76481. else {
  76482. _this._initialQuaternion[axisName] *= -1;
  76483. }
  76484. });
  76485. this._initialQuaternion.normalize();
  76486. //force rotation update
  76487. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76488. };
  76489. return DeviceOrientationCamera;
  76490. }(BABYLON.FreeCamera));
  76491. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76492. })(BABYLON || (BABYLON = {}));
  76493. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76494. var BABYLON;
  76495. (function (BABYLON) {
  76496. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76497. __extends(VRDeviceOrientationFreeCamera, _super);
  76498. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76499. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76500. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76501. var _this = _super.call(this, name, position, scene) || this;
  76502. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76503. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76504. return _this;
  76505. }
  76506. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76507. return "VRDeviceOrientationFreeCamera";
  76508. };
  76509. return VRDeviceOrientationFreeCamera;
  76510. }(BABYLON.DeviceOrientationCamera));
  76511. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76512. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76513. __extends(VRDeviceOrientationGamepadCamera, _super);
  76514. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76515. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76516. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76517. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76518. _this.inputs.addGamepad();
  76519. return _this;
  76520. }
  76521. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76522. return "VRDeviceOrientationGamepadCamera";
  76523. };
  76524. return VRDeviceOrientationGamepadCamera;
  76525. }(VRDeviceOrientationFreeCamera));
  76526. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76527. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76528. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76529. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76530. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76531. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76532. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76533. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76534. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76535. _this.inputs.addVRDeviceOrientation();
  76536. return _this;
  76537. }
  76538. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76539. return "VRDeviceOrientationArcRotateCamera";
  76540. };
  76541. return VRDeviceOrientationArcRotateCamera;
  76542. }(BABYLON.ArcRotateCamera));
  76543. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76544. })(BABYLON || (BABYLON = {}));
  76545. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76546. var BABYLON;
  76547. (function (BABYLON) {
  76548. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76549. __extends(AnaglyphFreeCamera, _super);
  76550. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76551. var _this = _super.call(this, name, position, scene) || this;
  76552. _this.interaxialDistance = interaxialDistance;
  76553. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76554. return _this;
  76555. }
  76556. AnaglyphFreeCamera.prototype.getClassName = function () {
  76557. return "AnaglyphFreeCamera";
  76558. };
  76559. return AnaglyphFreeCamera;
  76560. }(BABYLON.FreeCamera));
  76561. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76562. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76563. __extends(AnaglyphArcRotateCamera, _super);
  76564. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76565. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76566. _this.interaxialDistance = interaxialDistance;
  76567. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76568. return _this;
  76569. }
  76570. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76571. return "AnaglyphArcRotateCamera";
  76572. };
  76573. return AnaglyphArcRotateCamera;
  76574. }(BABYLON.ArcRotateCamera));
  76575. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76576. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76577. __extends(AnaglyphGamepadCamera, _super);
  76578. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76579. var _this = _super.call(this, name, position, scene) || this;
  76580. _this.interaxialDistance = interaxialDistance;
  76581. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76582. return _this;
  76583. }
  76584. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76585. return "AnaglyphGamepadCamera";
  76586. };
  76587. return AnaglyphGamepadCamera;
  76588. }(BABYLON.GamepadCamera));
  76589. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76590. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76591. __extends(AnaglyphUniversalCamera, _super);
  76592. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76593. var _this = _super.call(this, name, position, scene) || this;
  76594. _this.interaxialDistance = interaxialDistance;
  76595. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76596. return _this;
  76597. }
  76598. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76599. return "AnaglyphUniversalCamera";
  76600. };
  76601. return AnaglyphUniversalCamera;
  76602. }(BABYLON.UniversalCamera));
  76603. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76604. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76605. __extends(StereoscopicFreeCamera, _super);
  76606. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76607. var _this = _super.call(this, name, position, scene) || this;
  76608. _this.interaxialDistance = interaxialDistance;
  76609. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76610. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76611. return _this;
  76612. }
  76613. StereoscopicFreeCamera.prototype.getClassName = function () {
  76614. return "StereoscopicFreeCamera";
  76615. };
  76616. return StereoscopicFreeCamera;
  76617. }(BABYLON.FreeCamera));
  76618. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76619. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76620. __extends(StereoscopicArcRotateCamera, _super);
  76621. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76622. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76623. _this.interaxialDistance = interaxialDistance;
  76624. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76625. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76626. return _this;
  76627. }
  76628. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76629. return "StereoscopicArcRotateCamera";
  76630. };
  76631. return StereoscopicArcRotateCamera;
  76632. }(BABYLON.ArcRotateCamera));
  76633. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76634. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76635. __extends(StereoscopicGamepadCamera, _super);
  76636. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76637. var _this = _super.call(this, name, position, scene) || this;
  76638. _this.interaxialDistance = interaxialDistance;
  76639. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76640. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76641. return _this;
  76642. }
  76643. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76644. return "StereoscopicGamepadCamera";
  76645. };
  76646. return StereoscopicGamepadCamera;
  76647. }(BABYLON.GamepadCamera));
  76648. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76649. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76650. __extends(StereoscopicUniversalCamera, _super);
  76651. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76652. var _this = _super.call(this, name, position, scene) || this;
  76653. _this.interaxialDistance = interaxialDistance;
  76654. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76655. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76656. return _this;
  76657. }
  76658. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76659. return "StereoscopicUniversalCamera";
  76660. };
  76661. return StereoscopicUniversalCamera;
  76662. }(BABYLON.UniversalCamera));
  76663. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76664. })(BABYLON || (BABYLON = {}));
  76665. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76666. var BABYLON;
  76667. (function (BABYLON) {
  76668. /**
  76669. * Helps to quickly add VR support to an existing scene.
  76670. * See http://doc.babylonjs.com/how_to/webvr_helper
  76671. */
  76672. var VRExperienceHelper = /** @class */ (function () {
  76673. /**
  76674. * Instantiates a VRExperienceHelper.
  76675. * Helps to quickly add VR support to an existing scene.
  76676. * @param scene The scene the VRExperienceHelper belongs to.
  76677. * @param webVROptions Options to modify the vr experience helper's behavior.
  76678. */
  76679. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76680. if (webVROptions === void 0) { webVROptions = {}; }
  76681. var _this = this;
  76682. this.webVROptions = webVROptions;
  76683. // Can the system support WebVR, even if a headset isn't plugged in?
  76684. this._webVRsupported = false;
  76685. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76686. this._webVRready = false;
  76687. // Are we waiting for the requestPresent callback to complete?
  76688. this._webVRrequesting = false;
  76689. // Are we presenting to the headset right now?
  76690. this._webVRpresenting = false;
  76691. // Are we presenting in the fullscreen fallback?
  76692. this._fullscreenVRpresenting = false;
  76693. /**
  76694. * Observable raised when entering VR.
  76695. */
  76696. this.onEnteringVRObservable = new BABYLON.Observable();
  76697. /**
  76698. * Observable raised when exiting VR.
  76699. */
  76700. this.onExitingVRObservable = new BABYLON.Observable();
  76701. /**
  76702. * Observable raised when controller mesh is loaded.
  76703. */
  76704. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76705. this._useCustomVRButton = false;
  76706. this._teleportationRequested = false;
  76707. this._teleportationEnabledOnLeftController = false;
  76708. this._teleportationEnabledOnRightController = false;
  76709. this._interactionsEnabledOnLeftController = false;
  76710. this._interactionsEnabledOnRightController = false;
  76711. this._leftControllerReady = false;
  76712. this._rightControllerReady = false;
  76713. this._floorMeshesCollection = [];
  76714. this._teleportationAllowed = false;
  76715. this._rotationAllowed = true;
  76716. this._teleportationRequestInitiated = false;
  76717. this._teleportationBackRequestInitiated = false;
  76718. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76719. this._rotationRightAsked = false;
  76720. this._rotationLeftAsked = false;
  76721. this._isDefaultTeleportationTarget = true;
  76722. this._teleportationFillColor = "#444444";
  76723. this._teleportationBorderColor = "#FFFFFF";
  76724. this._rotationAngle = 0;
  76725. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76726. this._padSensibilityUp = 0.65;
  76727. this._padSensibilityDown = 0.35;
  76728. /**
  76729. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76730. */
  76731. this.onNewMeshSelected = new BABYLON.Observable();
  76732. /**
  76733. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76734. */
  76735. this.onNewMeshPicked = new BABYLON.Observable();
  76736. /**
  76737. * Observable raised before camera teleportation
  76738. */
  76739. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76740. /**
  76741. * Observable raised after camera teleportation
  76742. */
  76743. this.onAfterCameraTeleport = new BABYLON.Observable();
  76744. /**
  76745. * Observable raised when current selected mesh gets unselected
  76746. */
  76747. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76748. /**
  76749. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76750. */
  76751. this.teleportationEnabled = true;
  76752. this._pointerDownOnMeshAsked = false;
  76753. this._isActionableMesh = false;
  76754. this._teleportationInitialized = false;
  76755. this._interactionsEnabled = false;
  76756. this._interactionsRequested = false;
  76757. this._displayGaze = true;
  76758. this._displayLaserPointer = true;
  76759. this._dpadPressed = true;
  76760. this._onResize = function () {
  76761. _this.moveButtonToBottomRight();
  76762. if (_this._fullscreenVRpresenting && _this._webVRready) {
  76763. _this.exitVR();
  76764. }
  76765. };
  76766. this._onFullscreenChange = function () {
  76767. if (document.fullscreen !== undefined) {
  76768. _this._fullscreenVRpresenting = document.fullscreen;
  76769. }
  76770. else if (document.mozFullScreen !== undefined) {
  76771. _this._fullscreenVRpresenting = document.mozFullScreen;
  76772. }
  76773. else if (document.webkitIsFullScreen !== undefined) {
  76774. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  76775. }
  76776. else if (document.msIsFullScreen !== undefined) {
  76777. _this._fullscreenVRpresenting = document.msIsFullScreen;
  76778. }
  76779. if (!_this._fullscreenVRpresenting && _this._canvas) {
  76780. _this.exitVR();
  76781. if (!_this._useCustomVRButton) {
  76782. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  76783. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  76784. }
  76785. }
  76786. };
  76787. this.beforeRender = function () {
  76788. _this._castRayAndSelectObject();
  76789. };
  76790. this._onNewGamepadConnected = function (gamepad) {
  76791. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76792. if (gamepad.leftStick) {
  76793. gamepad.onleftstickchanged(function (stickValues) {
  76794. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  76795. // Listening to classic/xbox gamepad only if no VR controller is active
  76796. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  76797. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  76798. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  76799. _this._checkTeleportWithRay(stickValues);
  76800. _this._checkTeleportBackwards(stickValues);
  76801. }
  76802. }
  76803. });
  76804. }
  76805. if (gamepad.rightStick) {
  76806. gamepad.onrightstickchanged(function (stickValues) {
  76807. if (_this._teleportationInitialized) {
  76808. _this._checkRotate(stickValues);
  76809. }
  76810. });
  76811. }
  76812. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  76813. gamepad.onbuttondown(function (buttonPressed) {
  76814. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76815. _this._selectionPointerDown();
  76816. }
  76817. });
  76818. gamepad.onbuttonup(function (buttonPressed) {
  76819. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76820. _this._selectionPointerUp();
  76821. }
  76822. });
  76823. }
  76824. }
  76825. else {
  76826. var webVRController = gamepad;
  76827. _this._tryEnableInteractionOnController(webVRController);
  76828. }
  76829. };
  76830. // 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
  76831. this._tryEnableInteractionOnController = function (webVRController) {
  76832. if (webVRController.hand === "left") {
  76833. _this._leftControllerReady = true;
  76834. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  76835. _this._enableInteractionOnController(webVRController);
  76836. }
  76837. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  76838. _this._enableTeleportationOnController(webVRController);
  76839. }
  76840. }
  76841. if (webVRController.hand === "right") {
  76842. _this._rightControllerReady = true;
  76843. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  76844. _this._enableInteractionOnController(webVRController);
  76845. }
  76846. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  76847. _this._enableTeleportationOnController(webVRController);
  76848. }
  76849. }
  76850. };
  76851. this._onNewGamepadDisconnected = function (gamepad) {
  76852. if (gamepad instanceof BABYLON.WebVRController) {
  76853. if (gamepad.hand === "left") {
  76854. _this._interactionsEnabledOnLeftController = false;
  76855. _this._teleportationEnabledOnLeftController = false;
  76856. _this._leftControllerReady = false;
  76857. if (_this._leftLaserPointer) {
  76858. _this._leftLaserPointer.dispose();
  76859. }
  76860. }
  76861. if (gamepad.hand === "right") {
  76862. _this._interactionsEnabledOnRightController = false;
  76863. _this._teleportationEnabledOnRightController = false;
  76864. _this._rightControllerReady = false;
  76865. if (_this._rightLaserPointer) {
  76866. _this._rightLaserPointer.dispose();
  76867. }
  76868. }
  76869. }
  76870. };
  76871. this._workingVector = BABYLON.Vector3.Zero();
  76872. this._workingQuaternion = BABYLON.Quaternion.Identity();
  76873. this._workingMatrix = BABYLON.Matrix.Identity();
  76874. this._scene = scene;
  76875. this._canvas = scene.getEngine().getRenderingCanvas();
  76876. // Parse options
  76877. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  76878. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  76879. }
  76880. if (webVROptions.createDeviceOrientationCamera === undefined) {
  76881. webVROptions.createDeviceOrientationCamera = true;
  76882. }
  76883. if (webVROptions.defaultHeight === undefined) {
  76884. webVROptions.defaultHeight = 1.7;
  76885. }
  76886. if (webVROptions.useCustomVRButton) {
  76887. this._useCustomVRButton = true;
  76888. if (webVROptions.customVRButton) {
  76889. this._btnVR = webVROptions.customVRButton;
  76890. }
  76891. }
  76892. if (webVROptions.rayLength) {
  76893. this._rayLength = webVROptions.rayLength;
  76894. }
  76895. this._defaultHeight = webVROptions.defaultHeight;
  76896. // Set position
  76897. if (this._scene.activeCamera) {
  76898. this._position = this._scene.activeCamera.position.clone();
  76899. }
  76900. else {
  76901. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  76902. }
  76903. // Set non-vr camera
  76904. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  76905. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  76906. // Copy data from existing camera
  76907. if (this._scene.activeCamera) {
  76908. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  76909. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  76910. // Set rotation from previous camera
  76911. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  76912. var targetCamera = this._scene.activeCamera;
  76913. if (targetCamera.rotationQuaternion) {
  76914. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  76915. }
  76916. else {
  76917. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  76918. }
  76919. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  76920. }
  76921. }
  76922. this._scene.activeCamera = this._deviceOrientationCamera;
  76923. if (this._canvas) {
  76924. this._scene.activeCamera.attachControl(this._canvas);
  76925. }
  76926. }
  76927. else {
  76928. this._existingCamera = this._scene.activeCamera;
  76929. }
  76930. // Create VR cameras
  76931. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76932. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  76933. }
  76934. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  76935. this._webVRCamera.useStandingMatrix();
  76936. // Create default button
  76937. if (!this._useCustomVRButton) {
  76938. this._btnVR = document.createElement("BUTTON");
  76939. this._btnVR.className = "babylonVRicon";
  76940. this._btnVR.id = "babylonVRiconbtn";
  76941. this._btnVR.title = "Click to switch to VR";
  76942. 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) }";
  76943. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  76944. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  76945. // css += ".babylonVRicon.vrdisplaysupported { }";
  76946. // css += ".babylonVRicon.vrdisplayready { }";
  76947. // css += ".babylonVRicon.vrdisplayrequesting { }";
  76948. var style = document.createElement('style');
  76949. style.appendChild(document.createTextNode(css));
  76950. document.getElementsByTagName('head')[0].appendChild(style);
  76951. this.moveButtonToBottomRight();
  76952. }
  76953. // VR button click event
  76954. if (this._btnVR) {
  76955. this._btnVR.addEventListener("click", function () {
  76956. if (!_this.isInVRMode) {
  76957. _this.enterVR();
  76958. }
  76959. else {
  76960. _this.exitVR();
  76961. }
  76962. });
  76963. }
  76964. // Window events
  76965. window.addEventListener("resize", this._onResize);
  76966. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  76967. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  76968. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  76969. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  76970. // Display vr button when headset is connected
  76971. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76972. this.displayVRButton();
  76973. }
  76974. else {
  76975. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  76976. if (e.vrDisplay) {
  76977. _this.displayVRButton();
  76978. }
  76979. });
  76980. }
  76981. // Exiting VR mode using 'ESC' key on desktop
  76982. this._onKeyDown = function (event) {
  76983. if (event.keyCode === 27 && _this.isInVRMode) {
  76984. _this.exitVR();
  76985. }
  76986. };
  76987. document.addEventListener("keydown", this._onKeyDown);
  76988. // Exiting VR mode double tapping the touch screen
  76989. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  76990. if (_this.isInVRMode) {
  76991. _this.exitVR();
  76992. if (_this._fullscreenVRpresenting) {
  76993. _this._scene.getEngine().switchFullscreen(true);
  76994. }
  76995. }
  76996. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  76997. // Listen for WebVR display changes
  76998. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  76999. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  77000. this._onVRRequestPresentStart = function () {
  77001. _this._webVRrequesting = true;
  77002. _this.updateButtonVisibility();
  77003. };
  77004. this._onVRRequestPresentComplete = function (success) {
  77005. _this._webVRrequesting = false;
  77006. _this.updateButtonVisibility();
  77007. };
  77008. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  77009. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  77010. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  77011. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77012. scene.onDisposeObservable.add(function () {
  77013. _this.dispose();
  77014. });
  77015. // Gamepad connection events
  77016. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  77017. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  77018. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  77019. this.updateButtonVisibility();
  77020. //create easing functions
  77021. this._circleEase = new BABYLON.CircleEase();
  77022. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77023. }
  77024. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  77025. /** Return this.onEnteringVRObservable
  77026. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  77027. */
  77028. get: function () {
  77029. return this.onEnteringVRObservable;
  77030. },
  77031. enumerable: true,
  77032. configurable: true
  77033. });
  77034. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  77035. /** Return this.onExitingVRObservable
  77036. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  77037. */
  77038. get: function () {
  77039. return this.onExitingVRObservable;
  77040. },
  77041. enumerable: true,
  77042. configurable: true
  77043. });
  77044. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  77045. /** Return this.onControllerMeshLoadedObservable
  77046. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  77047. */
  77048. get: function () {
  77049. return this.onControllerMeshLoadedObservable;
  77050. },
  77051. enumerable: true,
  77052. configurable: true
  77053. });
  77054. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  77055. /**
  77056. * The mesh used to display where the user is going to teleport.
  77057. */
  77058. get: function () {
  77059. return this._teleportationTarget;
  77060. },
  77061. /**
  77062. * Sets the mesh to be used to display where the user is going to teleport.
  77063. */
  77064. set: function (value) {
  77065. if (value) {
  77066. value.name = "teleportationTarget";
  77067. this._isDefaultTeleportationTarget = false;
  77068. this._teleportationTarget = value;
  77069. }
  77070. },
  77071. enumerable: true,
  77072. configurable: true
  77073. });
  77074. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  77075. /**
  77076. * If the ray of the gaze should be displayed.
  77077. */
  77078. get: function () {
  77079. return this._displayGaze;
  77080. },
  77081. /**
  77082. * Sets if the ray of the gaze should be displayed.
  77083. */
  77084. set: function (value) {
  77085. this._displayGaze = value;
  77086. if (!value) {
  77087. this._gazeTracker.isVisible = false;
  77088. }
  77089. },
  77090. enumerable: true,
  77091. configurable: true
  77092. });
  77093. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  77094. /**
  77095. * If the ray of the LaserPointer should be displayed.
  77096. */
  77097. get: function () {
  77098. return this._displayLaserPointer;
  77099. },
  77100. /**
  77101. * Sets if the ray of the LaserPointer should be displayed.
  77102. */
  77103. set: function (value) {
  77104. this._displayLaserPointer = value;
  77105. if (!value) {
  77106. if (this._rightLaserPointer) {
  77107. this._rightLaserPointer.isVisible = false;
  77108. }
  77109. if (this._leftLaserPointer) {
  77110. this._leftLaserPointer.isVisible = false;
  77111. }
  77112. }
  77113. else {
  77114. if (this._rightLaserPointer) {
  77115. this._rightLaserPointer.isVisible = true;
  77116. }
  77117. else if (this._leftLaserPointer) {
  77118. this._leftLaserPointer.isVisible = true;
  77119. }
  77120. }
  77121. },
  77122. enumerable: true,
  77123. configurable: true
  77124. });
  77125. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  77126. /**
  77127. * The deviceOrientationCamera used as the camera when not in VR.
  77128. */
  77129. get: function () {
  77130. return this._deviceOrientationCamera;
  77131. },
  77132. enumerable: true,
  77133. configurable: true
  77134. });
  77135. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  77136. /**
  77137. * Based on the current WebVR support, returns the current VR camera used.
  77138. */
  77139. get: function () {
  77140. if (this._webVRready) {
  77141. return this._webVRCamera;
  77142. }
  77143. else {
  77144. return this._scene.activeCamera;
  77145. }
  77146. },
  77147. enumerable: true,
  77148. configurable: true
  77149. });
  77150. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  77151. /**
  77152. * The webVRCamera which is used when in VR.
  77153. */
  77154. get: function () {
  77155. return this._webVRCamera;
  77156. },
  77157. enumerable: true,
  77158. configurable: true
  77159. });
  77160. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  77161. /**
  77162. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  77163. */
  77164. get: function () {
  77165. return this._vrDeviceOrientationCamera;
  77166. },
  77167. enumerable: true,
  77168. configurable: true
  77169. });
  77170. // Raised when one of the controller has loaded successfully its associated default mesh
  77171. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  77172. this._tryEnableInteractionOnController(webVRController);
  77173. try {
  77174. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  77175. }
  77176. catch (err) {
  77177. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  77178. }
  77179. };
  77180. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  77181. /**
  77182. * Gets a value indicating if we are currently in VR mode.
  77183. */
  77184. get: function () {
  77185. return this._webVRpresenting || this._fullscreenVRpresenting;
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  77191. var vrDisplay = this._scene.getEngine().getVRDevice();
  77192. if (vrDisplay) {
  77193. var wasPresenting = this._webVRpresenting;
  77194. // A VR display is connected
  77195. this._webVRpresenting = vrDisplay.isPresenting;
  77196. if (wasPresenting && !this._webVRpresenting)
  77197. this.exitVR();
  77198. }
  77199. else {
  77200. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  77201. }
  77202. this.updateButtonVisibility();
  77203. };
  77204. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  77205. this._webVRsupported = eventArgs.vrSupported;
  77206. this._webVRready = !!eventArgs.vrDisplay;
  77207. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  77208. this.updateButtonVisibility();
  77209. };
  77210. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  77211. if (this._canvas && !this._useCustomVRButton) {
  77212. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  77213. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  77214. }
  77215. };
  77216. VRExperienceHelper.prototype.displayVRButton = function () {
  77217. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  77218. document.body.appendChild(this._btnVR);
  77219. this._btnVRDisplayed = true;
  77220. }
  77221. };
  77222. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  77223. if (!this._btnVR || this._useCustomVRButton) {
  77224. return;
  77225. }
  77226. this._btnVR.className = "babylonVRicon";
  77227. if (this.isInVRMode) {
  77228. this._btnVR.className += " vrdisplaypresenting";
  77229. }
  77230. else {
  77231. if (this._webVRready)
  77232. this._btnVR.className += " vrdisplayready";
  77233. if (this._webVRsupported)
  77234. this._btnVR.className += " vrdisplaysupported";
  77235. if (this._webVRrequesting)
  77236. this._btnVR.className += " vrdisplayrequesting";
  77237. }
  77238. };
  77239. /**
  77240. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  77241. * Otherwise, will use the fullscreen API.
  77242. */
  77243. VRExperienceHelper.prototype.enterVR = function () {
  77244. if (this.onEnteringVRObservable) {
  77245. try {
  77246. this.onEnteringVRObservable.notifyObservers(this);
  77247. }
  77248. catch (err) {
  77249. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  77250. }
  77251. }
  77252. if (this._scene.activeCamera) {
  77253. this._position = this._scene.activeCamera.position.clone();
  77254. // make sure that we return to the last active camera
  77255. this._existingCamera = this._scene.activeCamera;
  77256. }
  77257. if (this._webVRrequesting)
  77258. return;
  77259. // If WebVR is supported and a headset is connected
  77260. if (this._webVRready) {
  77261. if (!this._webVRpresenting) {
  77262. this._webVRCamera.position = this._position;
  77263. this._scene.activeCamera = this._webVRCamera;
  77264. }
  77265. }
  77266. else if (this._vrDeviceOrientationCamera) {
  77267. this._vrDeviceOrientationCamera.position = this._position;
  77268. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  77269. this._scene.getEngine().switchFullscreen(true);
  77270. this.updateButtonVisibility();
  77271. }
  77272. if (this._scene.activeCamera && this._canvas) {
  77273. this._scene.activeCamera.attachControl(this._canvas);
  77274. }
  77275. if (this._interactionsEnabled) {
  77276. this._scene.registerBeforeRender(this.beforeRender);
  77277. }
  77278. };
  77279. /**
  77280. * Attempt to exit VR, or fullscreen.
  77281. */
  77282. VRExperienceHelper.prototype.exitVR = function () {
  77283. if (this.onExitingVRObservable) {
  77284. try {
  77285. this.onExitingVRObservable.notifyObservers(this);
  77286. }
  77287. catch (err) {
  77288. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  77289. }
  77290. }
  77291. if (this._webVRpresenting) {
  77292. this._scene.getEngine().disableVR();
  77293. }
  77294. if (this._scene.activeCamera) {
  77295. this._position = this._scene.activeCamera.position.clone();
  77296. }
  77297. if (this._deviceOrientationCamera) {
  77298. this._deviceOrientationCamera.position = this._position;
  77299. this._scene.activeCamera = this._deviceOrientationCamera;
  77300. if (this._canvas) {
  77301. this._scene.activeCamera.attachControl(this._canvas);
  77302. }
  77303. }
  77304. else if (this._existingCamera) {
  77305. this._existingCamera.position = this._position;
  77306. this._scene.activeCamera = this._existingCamera;
  77307. }
  77308. this.updateButtonVisibility();
  77309. if (this._interactionsEnabled) {
  77310. this._scene.unregisterBeforeRender(this.beforeRender);
  77311. }
  77312. };
  77313. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  77314. /**
  77315. * The position of the vr experience helper.
  77316. */
  77317. get: function () {
  77318. return this._position;
  77319. },
  77320. /**
  77321. * Sets the position of the vr experience helper.
  77322. */
  77323. set: function (value) {
  77324. this._position = value;
  77325. if (this._scene.activeCamera) {
  77326. this._scene.activeCamera.position = value;
  77327. }
  77328. },
  77329. enumerable: true,
  77330. configurable: true
  77331. });
  77332. /**
  77333. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  77334. */
  77335. VRExperienceHelper.prototype.enableInteractions = function () {
  77336. var _this = this;
  77337. if (!this._interactionsEnabled) {
  77338. this._interactionsRequested = true;
  77339. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77340. this._enableInteractionOnController(this._webVRCamera.leftController);
  77341. }
  77342. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77343. this._enableInteractionOnController(this._webVRCamera.rightController);
  77344. }
  77345. this._createGazeTracker();
  77346. this.raySelectionPredicate = function (mesh) {
  77347. return mesh.isVisible;
  77348. };
  77349. this.meshSelectionPredicate = function (mesh) {
  77350. return true;
  77351. };
  77352. this._raySelectionPredicate = function (mesh) {
  77353. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  77354. && mesh.name.indexOf("teleportationTarget") === -1
  77355. && mesh.name.indexOf("torusTeleportation") === -1
  77356. && mesh.name.indexOf("laserPointer") === -1)) {
  77357. return _this.raySelectionPredicate(mesh);
  77358. }
  77359. return false;
  77360. };
  77361. this._interactionsEnabled = true;
  77362. }
  77363. };
  77364. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  77365. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  77366. if (this._floorMeshesCollection[i].id === mesh.id) {
  77367. return true;
  77368. }
  77369. }
  77370. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  77371. return true;
  77372. }
  77373. return false;
  77374. };
  77375. /**
  77376. * Adds a floor mesh to be used for teleportation.
  77377. * @param floorMesh the mesh to be used for teleportation.
  77378. */
  77379. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  77380. if (!this._floorMeshesCollection) {
  77381. return;
  77382. }
  77383. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  77384. return;
  77385. }
  77386. this._floorMeshesCollection.push(floorMesh);
  77387. };
  77388. /**
  77389. * Removes a floor mesh from being used for teleportation.
  77390. * @param floorMesh the mesh to be removed.
  77391. */
  77392. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  77393. if (!this._floorMeshesCollection) {
  77394. return;
  77395. }
  77396. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  77397. if (meshIndex !== -1) {
  77398. this._floorMeshesCollection.splice(meshIndex, 1);
  77399. }
  77400. };
  77401. /**
  77402. * Enables interactions and teleportation using the VR controllers and gaze.
  77403. * @param vrTeleportationOptions options to modify teleportation behavior.
  77404. */
  77405. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  77406. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  77407. if (!this._teleportationInitialized) {
  77408. this._teleportationRequested = true;
  77409. this.enableInteractions();
  77410. if (vrTeleportationOptions.floorMeshName) {
  77411. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  77412. }
  77413. if (vrTeleportationOptions.floorMeshes) {
  77414. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  77415. }
  77416. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77417. this._enableTeleportationOnController(this._webVRCamera.leftController);
  77418. }
  77419. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77420. this._enableTeleportationOnController(this._webVRCamera.rightController);
  77421. }
  77422. // Creates an image processing post process for the vignette not relying
  77423. // on the main scene configuration for image processing to reduce setup and spaces
  77424. // (gamma/linear) conflicts.
  77425. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  77426. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77427. imageProcessingConfiguration.vignetteEnabled = true;
  77428. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  77429. this._webVRCamera.detachPostProcess(this._postProcessMove);
  77430. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  77431. this._teleportationInitialized = true;
  77432. if (this._isDefaultTeleportationTarget) {
  77433. this._createTeleportationCircles();
  77434. }
  77435. }
  77436. };
  77437. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  77438. var _this = this;
  77439. var controllerMesh = webVRController.mesh;
  77440. if (controllerMesh) {
  77441. var makeNotPick = function (root) {
  77442. root.name += " laserPointer";
  77443. root.getChildMeshes().forEach(function (c) {
  77444. makeNotPick(c);
  77445. });
  77446. };
  77447. makeNotPick(controllerMesh);
  77448. var childMeshes = controllerMesh.getChildMeshes();
  77449. for (var i = 0; i < childMeshes.length; i++) {
  77450. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  77451. controllerMesh = childMeshes[i];
  77452. break;
  77453. }
  77454. }
  77455. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77456. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77457. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77458. laserPointerMaterial.alpha = 0.6;
  77459. laserPointer.material = laserPointerMaterial;
  77460. laserPointer.rotation.x = Math.PI / 2;
  77461. laserPointer.parent = controllerMesh;
  77462. laserPointer.position.z = -0.5;
  77463. laserPointer.isVisible = false;
  77464. if (webVRController.hand === "left") {
  77465. this._leftLaserPointer = laserPointer;
  77466. this._interactionsEnabledOnLeftController = true;
  77467. if (!this._rightLaserPointer) {
  77468. this._leftLaserPointer.isVisible = true;
  77469. }
  77470. }
  77471. else {
  77472. this._rightLaserPointer = laserPointer;
  77473. this._interactionsEnabledOnRightController = true;
  77474. if (!this._leftLaserPointer) {
  77475. this._rightLaserPointer.isVisible = true;
  77476. }
  77477. }
  77478. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77479. // Enabling / disabling laserPointer
  77480. if (_this._displayLaserPointer && stateObject.value === 1) {
  77481. laserPointer.isVisible = !laserPointer.isVisible;
  77482. // Laser pointer can only be active on left or right, not both at the same time
  77483. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77484. _this._rightLaserPointer.isVisible = false;
  77485. }
  77486. else if (_this._leftLaserPointer) {
  77487. _this._leftLaserPointer.isVisible = false;
  77488. }
  77489. }
  77490. });
  77491. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77492. if (!_this._pointerDownOnMeshAsked) {
  77493. if (stateObject.value > _this._padSensibilityUp) {
  77494. _this._selectionPointerDown();
  77495. }
  77496. }
  77497. else if (stateObject.value < _this._padSensibilityDown) {
  77498. _this._selectionPointerUp();
  77499. }
  77500. });
  77501. }
  77502. };
  77503. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77504. if (webVRController === void 0) { webVRController = null; }
  77505. if (!this._teleportationRequestInitiated) {
  77506. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77507. if (webVRController) {
  77508. // If laser pointer wasn't enabled yet
  77509. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77510. this._leftLaserPointer.isVisible = true;
  77511. if (this._rightLaserPointer) {
  77512. this._rightLaserPointer.isVisible = false;
  77513. }
  77514. }
  77515. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77516. this._rightLaserPointer.isVisible = true;
  77517. if (this._leftLaserPointer) {
  77518. this._leftLaserPointer.isVisible = false;
  77519. }
  77520. }
  77521. }
  77522. this._teleportationRequestInitiated = true;
  77523. }
  77524. }
  77525. else {
  77526. // Listening to the proper controller values changes to confirm teleportation
  77527. if (webVRController == null
  77528. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77529. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77530. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77531. if (this._teleportationAllowed) {
  77532. this._teleportationAllowed = false;
  77533. this._teleportCamera();
  77534. }
  77535. this._teleportationRequestInitiated = false;
  77536. }
  77537. }
  77538. }
  77539. };
  77540. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77541. this._pointerDownOnMeshAsked = true;
  77542. if (this._currentMeshSelected && this._currentHit) {
  77543. this._scene.simulatePointerDown(this._currentHit);
  77544. }
  77545. };
  77546. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77547. if (this._currentMeshSelected && this._currentHit) {
  77548. this._scene.simulatePointerUp(this._currentHit);
  77549. }
  77550. this._pointerDownOnMeshAsked = false;
  77551. };
  77552. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77553. // Only rotate when user is not currently selecting a teleportation location
  77554. if (this._teleportationRequestInitiated) {
  77555. return;
  77556. }
  77557. if (!this._rotationLeftAsked) {
  77558. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77559. this._rotationLeftAsked = true;
  77560. if (this._rotationAllowed) {
  77561. this._rotateCamera(false);
  77562. }
  77563. }
  77564. }
  77565. else {
  77566. if (stateObject.x > -this._padSensibilityDown) {
  77567. this._rotationLeftAsked = false;
  77568. }
  77569. }
  77570. if (!this._rotationRightAsked) {
  77571. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77572. this._rotationRightAsked = true;
  77573. if (this._rotationAllowed) {
  77574. this._rotateCamera(true);
  77575. }
  77576. }
  77577. }
  77578. else {
  77579. if (stateObject.x < this._padSensibilityDown) {
  77580. this._rotationRightAsked = false;
  77581. }
  77582. }
  77583. };
  77584. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77585. // Only teleport backwards when user is not currently selecting a teleportation location
  77586. if (this._teleportationRequestInitiated) {
  77587. return;
  77588. }
  77589. // Teleport backwards
  77590. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77591. if (!this._teleportationBackRequestInitiated) {
  77592. if (!this.currentVRCamera) {
  77593. return;
  77594. }
  77595. // Get rotation and position of the current camera
  77596. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77597. var position = this.currentVRCamera.position;
  77598. // If the camera has device position, use that instead
  77599. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77600. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77601. position = this.currentVRCamera.devicePosition;
  77602. }
  77603. // Get matrix with only the y rotation of the device rotation
  77604. rotation.toEulerAnglesToRef(this._workingVector);
  77605. this._workingVector.z = 0;
  77606. this._workingVector.x = 0;
  77607. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77608. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77609. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77610. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77611. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77612. var ray = new BABYLON.Ray(position, this._workingVector);
  77613. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77614. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77615. this._teleportCamera(hit.pickedPoint);
  77616. }
  77617. this._teleportationBackRequestInitiated = true;
  77618. }
  77619. }
  77620. else {
  77621. this._teleportationBackRequestInitiated = false;
  77622. }
  77623. };
  77624. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77625. var _this = this;
  77626. var controllerMesh = webVRController.mesh;
  77627. if (controllerMesh) {
  77628. if (webVRController.hand === "left") {
  77629. if (!this._interactionsEnabledOnLeftController) {
  77630. this._enableInteractionOnController(webVRController);
  77631. }
  77632. this._teleportationEnabledOnLeftController = true;
  77633. }
  77634. else {
  77635. if (!this._interactionsEnabledOnRightController) {
  77636. this._enableInteractionOnController(webVRController);
  77637. }
  77638. this._teleportationEnabledOnRightController = true;
  77639. }
  77640. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77641. this._dpadPressed = false;
  77642. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77643. _this._dpadPressed = stateObject.pressed;
  77644. if (!_this._dpadPressed) {
  77645. _this._rotationLeftAsked = false;
  77646. _this._rotationRightAsked = false;
  77647. _this._teleportationBackRequestInitiated = false;
  77648. }
  77649. });
  77650. }
  77651. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77652. if (_this.teleportationEnabled) {
  77653. _this._checkTeleportBackwards(stateObject);
  77654. _this._checkTeleportWithRay(stateObject, webVRController);
  77655. }
  77656. _this._checkRotate(stateObject);
  77657. });
  77658. }
  77659. };
  77660. // Gaze support used to point to teleport or to interact with an object
  77661. VRExperienceHelper.prototype._createGazeTracker = function () {
  77662. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77663. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77664. this._gazeTracker.isPickable = false;
  77665. this._gazeTracker.isVisible = false;
  77666. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77667. targetMat.specularColor = BABYLON.Color3.Black();
  77668. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77669. targetMat.backFaceCulling = false;
  77670. this._gazeTracker.material = targetMat;
  77671. };
  77672. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77673. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77674. this._teleportationTarget.isPickable = false;
  77675. var length = 512;
  77676. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77677. dynamicTexture.hasAlpha = true;
  77678. var context = dynamicTexture.getContext();
  77679. var centerX = length / 2;
  77680. var centerY = length / 2;
  77681. var radius = 200;
  77682. context.beginPath();
  77683. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77684. context.fillStyle = this._teleportationFillColor;
  77685. context.fill();
  77686. context.lineWidth = 10;
  77687. context.strokeStyle = this._teleportationBorderColor;
  77688. context.stroke();
  77689. context.closePath();
  77690. dynamicTexture.update();
  77691. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77692. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77693. this._teleportationTarget.material = teleportationCircleMaterial;
  77694. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77695. torus.isPickable = false;
  77696. torus.parent = this._teleportationTarget;
  77697. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77698. var keys = [];
  77699. keys.push({
  77700. frame: 0,
  77701. value: 0
  77702. });
  77703. keys.push({
  77704. frame: 30,
  77705. value: 0.4
  77706. });
  77707. keys.push({
  77708. frame: 60,
  77709. value: 0
  77710. });
  77711. animationInnerCircle.setKeys(keys);
  77712. var easingFunction = new BABYLON.SineEase();
  77713. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77714. animationInnerCircle.setEasingFunction(easingFunction);
  77715. torus.animations = [];
  77716. torus.animations.push(animationInnerCircle);
  77717. this._scene.beginAnimation(torus, 0, 60, true);
  77718. this._hideTeleportationTarget();
  77719. };
  77720. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77721. if (this._teleportationInitialized) {
  77722. this._teleportationTarget.isVisible = true;
  77723. if (this._isDefaultTeleportationTarget) {
  77724. this._teleportationTarget.getChildren()[0].isVisible = true;
  77725. }
  77726. }
  77727. };
  77728. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77729. if (this._teleportationInitialized) {
  77730. this._teleportationTarget.isVisible = false;
  77731. if (this._isDefaultTeleportationTarget) {
  77732. this._teleportationTarget.getChildren()[0].isVisible = false;
  77733. }
  77734. }
  77735. };
  77736. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77737. var _this = this;
  77738. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77739. return;
  77740. }
  77741. if (right) {
  77742. this._rotationAngle++;
  77743. }
  77744. else {
  77745. this._rotationAngle--;
  77746. }
  77747. this.currentVRCamera.animations = [];
  77748. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77749. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77750. var animationRotationKeys = [];
  77751. animationRotationKeys.push({
  77752. frame: 0,
  77753. value: this.currentVRCamera.rotationQuaternion
  77754. });
  77755. animationRotationKeys.push({
  77756. frame: 6,
  77757. value: target
  77758. });
  77759. animationRotation.setKeys(animationRotationKeys);
  77760. animationRotation.setEasingFunction(this._circleEase);
  77761. this.currentVRCamera.animations.push(animationRotation);
  77762. this._postProcessMove.animations = [];
  77763. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77764. var vignetteWeightKeys = [];
  77765. vignetteWeightKeys.push({
  77766. frame: 0,
  77767. value: 0
  77768. });
  77769. vignetteWeightKeys.push({
  77770. frame: 3,
  77771. value: 4
  77772. });
  77773. vignetteWeightKeys.push({
  77774. frame: 6,
  77775. value: 0
  77776. });
  77777. animationPP.setKeys(vignetteWeightKeys);
  77778. animationPP.setEasingFunction(this._circleEase);
  77779. this._postProcessMove.animations.push(animationPP);
  77780. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77781. var vignetteStretchKeys = [];
  77782. vignetteStretchKeys.push({
  77783. frame: 0,
  77784. value: 0
  77785. });
  77786. vignetteStretchKeys.push({
  77787. frame: 3,
  77788. value: 10
  77789. });
  77790. vignetteStretchKeys.push({
  77791. frame: 6,
  77792. value: 0
  77793. });
  77794. animationPP2.setKeys(vignetteStretchKeys);
  77795. animationPP2.setEasingFunction(this._circleEase);
  77796. this._postProcessMove.animations.push(animationPP2);
  77797. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77798. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77799. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77800. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  77801. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77802. });
  77803. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  77804. };
  77805. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  77806. if (hit.pickedPoint) {
  77807. this._teleportationAllowed = true;
  77808. if (this._teleportationRequestInitiated) {
  77809. this._displayTeleportationTarget();
  77810. }
  77811. else {
  77812. this._hideTeleportationTarget();
  77813. }
  77814. this._haloCenter.copyFrom(hit.pickedPoint);
  77815. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  77816. var pickNormal = hit.getNormal(true, false);
  77817. if (pickNormal) {
  77818. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77819. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77820. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  77821. }
  77822. this._teleportationTarget.position.y += 0.1;
  77823. }
  77824. };
  77825. VRExperienceHelper.prototype._teleportCamera = function (location) {
  77826. var _this = this;
  77827. if (location === void 0) { location = null; }
  77828. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77829. return;
  77830. }
  77831. if (!location) {
  77832. location = this._haloCenter;
  77833. }
  77834. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  77835. // offset of the headset from the anchor.
  77836. if (this.webVRCamera.leftCamera) {
  77837. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  77838. this._workingVector.subtractInPlace(this.webVRCamera.position);
  77839. location.subtractToRef(this._workingVector, this._workingVector);
  77840. }
  77841. else {
  77842. this._workingVector.copyFrom(location);
  77843. }
  77844. // Add height to account for user's height offset
  77845. if (this.isInVRMode) {
  77846. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  77847. }
  77848. else {
  77849. this._workingVector.y += this._defaultHeight;
  77850. }
  77851. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  77852. // Create animation from the camera's position to the new location
  77853. this.currentVRCamera.animations = [];
  77854. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77855. var animationCameraTeleportationKeys = [{
  77856. frame: 0,
  77857. value: this.currentVRCamera.position
  77858. },
  77859. {
  77860. frame: 11,
  77861. value: this._workingVector
  77862. }
  77863. ];
  77864. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  77865. animationCameraTeleportation.setEasingFunction(this._circleEase);
  77866. this.currentVRCamera.animations.push(animationCameraTeleportation);
  77867. this._postProcessMove.animations = [];
  77868. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77869. var vignetteWeightKeys = [];
  77870. vignetteWeightKeys.push({
  77871. frame: 0,
  77872. value: 0
  77873. });
  77874. vignetteWeightKeys.push({
  77875. frame: 5,
  77876. value: 8
  77877. });
  77878. vignetteWeightKeys.push({
  77879. frame: 11,
  77880. value: 0
  77881. });
  77882. animationPP.setKeys(vignetteWeightKeys);
  77883. this._postProcessMove.animations.push(animationPP);
  77884. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77885. var vignetteStretchKeys = [];
  77886. vignetteStretchKeys.push({
  77887. frame: 0,
  77888. value: 0
  77889. });
  77890. vignetteStretchKeys.push({
  77891. frame: 5,
  77892. value: 10
  77893. });
  77894. vignetteStretchKeys.push({
  77895. frame: 11,
  77896. value: 0
  77897. });
  77898. animationPP2.setKeys(vignetteStretchKeys);
  77899. this._postProcessMove.animations.push(animationPP2);
  77900. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77901. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77902. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77903. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  77904. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77905. });
  77906. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  77907. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  77908. });
  77909. };
  77910. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  77911. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77912. return;
  77913. }
  77914. var ray;
  77915. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  77916. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  77917. }
  77918. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  77919. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  77920. }
  77921. else {
  77922. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  77923. }
  77924. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77925. // Moving the gazeTracker on the mesh face targetted
  77926. if (hit && hit.pickedPoint) {
  77927. if (this._displayGaze) {
  77928. var multiplier = 1;
  77929. this._gazeTracker.isVisible = true;
  77930. if (this._isActionableMesh) {
  77931. multiplier = 3;
  77932. }
  77933. this._gazeTracker.scaling.x = hit.distance * multiplier;
  77934. this._gazeTracker.scaling.y = hit.distance * multiplier;
  77935. this._gazeTracker.scaling.z = hit.distance * multiplier;
  77936. var pickNormal = hit.getNormal();
  77937. // To avoid z-fighting
  77938. var deltaFighting = 0.002;
  77939. if (pickNormal) {
  77940. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77941. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77942. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  77943. }
  77944. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  77945. if (this._gazeTracker.position.x < 0) {
  77946. this._gazeTracker.position.x += deltaFighting;
  77947. }
  77948. else {
  77949. this._gazeTracker.position.x -= deltaFighting;
  77950. }
  77951. if (this._gazeTracker.position.y < 0) {
  77952. this._gazeTracker.position.y += deltaFighting;
  77953. }
  77954. else {
  77955. this._gazeTracker.position.y -= deltaFighting;
  77956. }
  77957. if (this._gazeTracker.position.z < 0) {
  77958. this._gazeTracker.position.z += deltaFighting;
  77959. }
  77960. else {
  77961. this._gazeTracker.position.z -= deltaFighting;
  77962. }
  77963. }
  77964. // Changing the size of the laser pointer based on the distance from the targetted point
  77965. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  77966. this._rightLaserPointer.scaling.y = hit.distance;
  77967. this._rightLaserPointer.position.z = -hit.distance / 2;
  77968. }
  77969. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  77970. this._leftLaserPointer.scaling.y = hit.distance;
  77971. this._leftLaserPointer.position.z = -hit.distance / 2;
  77972. }
  77973. }
  77974. else {
  77975. this._gazeTracker.isVisible = false;
  77976. }
  77977. if (hit && hit.pickedMesh) {
  77978. this._currentHit = hit;
  77979. if (this._pointerDownOnMeshAsked) {
  77980. this._scene.simulatePointerMove(this._currentHit);
  77981. }
  77982. // The object selected is the floor, we're in a teleportation scenario
  77983. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  77984. // Moving the teleportation area to this targetted point
  77985. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  77986. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  77987. this._notifySelectedMeshUnselected();
  77988. }
  77989. this._currentMeshSelected = null;
  77990. this._moveTeleportationSelectorTo(hit);
  77991. return;
  77992. }
  77993. // If not, we're in a selection scenario
  77994. this._hideTeleportationTarget();
  77995. this._teleportationAllowed = false;
  77996. if (hit.pickedMesh !== this._currentMeshSelected) {
  77997. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  77998. this.onNewMeshPicked.notifyObservers(hit);
  77999. this._currentMeshSelected = hit.pickedMesh;
  78000. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  78001. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  78002. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  78003. this._isActionableMesh = true;
  78004. }
  78005. else {
  78006. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78007. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78008. this._isActionableMesh = false;
  78009. }
  78010. try {
  78011. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  78012. }
  78013. catch (err) {
  78014. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  78015. }
  78016. }
  78017. else {
  78018. this._notifySelectedMeshUnselected();
  78019. this._currentMeshSelected = null;
  78020. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78021. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78022. }
  78023. }
  78024. }
  78025. else {
  78026. this._currentHit = null;
  78027. this._notifySelectedMeshUnselected();
  78028. this._currentMeshSelected = null;
  78029. this._teleportationAllowed = false;
  78030. this._hideTeleportationTarget();
  78031. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78032. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78033. }
  78034. };
  78035. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  78036. if (this._currentMeshSelected) {
  78037. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  78038. }
  78039. };
  78040. /**
  78041. * Sets the color of the laser ray from the vr controllers.
  78042. * @param color new color for the ray.
  78043. */
  78044. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  78045. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  78046. this._leftLaserPointer.material.emissiveColor = color;
  78047. }
  78048. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  78049. this._rightLaserPointer.material.emissiveColor = color;
  78050. }
  78051. };
  78052. /**
  78053. * Sets the color of the ray from the vr headsets gaze.
  78054. * @param color new color for the ray.
  78055. */
  78056. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  78057. if (this._gazeTracker.material) {
  78058. this._gazeTracker.material.emissiveColor = color;
  78059. }
  78060. };
  78061. /**
  78062. * Exits VR and disposes of the vr experience helper
  78063. */
  78064. VRExperienceHelper.prototype.dispose = function () {
  78065. if (this.isInVRMode) {
  78066. this.exitVR();
  78067. }
  78068. if (this._passProcessMove) {
  78069. this._passProcessMove.dispose();
  78070. }
  78071. if (this._postProcessMove) {
  78072. this._postProcessMove.dispose();
  78073. }
  78074. if (this._webVRCamera) {
  78075. this._webVRCamera.dispose();
  78076. }
  78077. if (this._vrDeviceOrientationCamera) {
  78078. this._vrDeviceOrientationCamera.dispose();
  78079. }
  78080. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  78081. document.body.removeChild(this._btnVR);
  78082. }
  78083. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  78084. this._deviceOrientationCamera.dispose();
  78085. }
  78086. if (this._gazeTracker) {
  78087. this._gazeTracker.dispose();
  78088. }
  78089. if (this._teleportationTarget) {
  78090. this._teleportationTarget.dispose();
  78091. }
  78092. this._floorMeshesCollection = [];
  78093. document.removeEventListener("keydown", this._onKeyDown);
  78094. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78095. window.removeEventListener("resize", this._onResize);
  78096. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  78097. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  78098. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  78099. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  78100. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  78101. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  78102. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  78103. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78104. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  78105. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  78106. this._scene.unregisterBeforeRender(this.beforeRender);
  78107. };
  78108. /**
  78109. * Gets the name of the VRExperienceHelper class
  78110. * @returns "VRExperienceHelper"
  78111. */
  78112. VRExperienceHelper.prototype.getClassName = function () {
  78113. return "VRExperienceHelper";
  78114. };
  78115. return VRExperienceHelper;
  78116. }());
  78117. BABYLON.VRExperienceHelper = VRExperienceHelper;
  78118. })(BABYLON || (BABYLON = {}));
  78119. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  78120. // Mainly based on these 2 articles :
  78121. // 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
  78122. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  78123. var BABYLON;
  78124. (function (BABYLON) {
  78125. var JoystickAxis;
  78126. (function (JoystickAxis) {
  78127. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  78128. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  78129. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  78130. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  78131. var VirtualJoystick = /** @class */ (function () {
  78132. function VirtualJoystick(leftJoystick) {
  78133. var _this = this;
  78134. if (leftJoystick) {
  78135. this._leftJoystick = true;
  78136. }
  78137. else {
  78138. this._leftJoystick = false;
  78139. }
  78140. VirtualJoystick._globalJoystickIndex++;
  78141. // By default left & right arrow keys are moving the X
  78142. // and up & down keys are moving the Y
  78143. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78144. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78145. this.reverseLeftRight = false;
  78146. this.reverseUpDown = false;
  78147. // collections of pointers
  78148. this._touches = new BABYLON.StringDictionary();
  78149. this.deltaPosition = BABYLON.Vector3.Zero();
  78150. this._joystickSensibility = 25;
  78151. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78152. this._onResize = function (evt) {
  78153. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  78154. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  78155. if (VirtualJoystick.vjCanvas) {
  78156. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  78157. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  78158. }
  78159. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  78160. };
  78161. // injecting a canvas element on top of the canvas 3D game
  78162. if (!VirtualJoystick.vjCanvas) {
  78163. window.addEventListener("resize", this._onResize, false);
  78164. VirtualJoystick.vjCanvas = document.createElement("canvas");
  78165. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  78166. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  78167. VirtualJoystick.vjCanvas.width = window.innerWidth;
  78168. VirtualJoystick.vjCanvas.height = window.innerHeight;
  78169. VirtualJoystick.vjCanvas.style.width = "100%";
  78170. VirtualJoystick.vjCanvas.style.height = "100%";
  78171. VirtualJoystick.vjCanvas.style.position = "absolute";
  78172. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  78173. VirtualJoystick.vjCanvas.style.top = "0px";
  78174. VirtualJoystick.vjCanvas.style.left = "0px";
  78175. VirtualJoystick.vjCanvas.style.zIndex = "5";
  78176. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  78177. // Support for jQuery PEP polyfill
  78178. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  78179. var context = VirtualJoystick.vjCanvas.getContext('2d');
  78180. if (!context) {
  78181. throw new Error("Unable to create canvas for virtual joystick");
  78182. }
  78183. VirtualJoystick.vjCanvasContext = context;
  78184. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  78185. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78186. document.body.appendChild(VirtualJoystick.vjCanvas);
  78187. }
  78188. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  78189. this.pressed = false;
  78190. // default joystick color
  78191. this._joystickColor = "cyan";
  78192. this._joystickPointerID = -1;
  78193. // current joystick position
  78194. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  78195. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  78196. // origin joystick position
  78197. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  78198. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  78199. this._onPointerDownHandlerRef = function (evt) {
  78200. _this._onPointerDown(evt);
  78201. };
  78202. this._onPointerMoveHandlerRef = function (evt) {
  78203. _this._onPointerMove(evt);
  78204. };
  78205. this._onPointerUpHandlerRef = function (evt) {
  78206. _this._onPointerUp(evt);
  78207. };
  78208. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  78209. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  78210. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  78211. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  78212. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  78213. evt.preventDefault(); // Disables system menu
  78214. }, false);
  78215. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78216. }
  78217. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  78218. this._joystickSensibility = newJoystickSensibility;
  78219. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78220. };
  78221. VirtualJoystick.prototype._onPointerDown = function (e) {
  78222. var positionOnScreenCondition;
  78223. e.preventDefault();
  78224. if (this._leftJoystick === true) {
  78225. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  78226. }
  78227. else {
  78228. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  78229. }
  78230. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  78231. // First contact will be dedicated to the virtual joystick
  78232. this._joystickPointerID = e.pointerId;
  78233. this._joystickPointerStartPos.x = e.clientX;
  78234. this._joystickPointerStartPos.y = e.clientY;
  78235. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  78236. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  78237. this._deltaJoystickVector.x = 0;
  78238. this._deltaJoystickVector.y = 0;
  78239. this.pressed = true;
  78240. this._touches.add(e.pointerId.toString(), e);
  78241. }
  78242. else {
  78243. // You can only trigger the action buttons with a joystick declared
  78244. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  78245. this._action();
  78246. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  78247. }
  78248. }
  78249. };
  78250. VirtualJoystick.prototype._onPointerMove = function (e) {
  78251. // If the current pointer is the one associated to the joystick (first touch contact)
  78252. if (this._joystickPointerID == e.pointerId) {
  78253. this._joystickPointerPos.x = e.clientX;
  78254. this._joystickPointerPos.y = e.clientY;
  78255. this._deltaJoystickVector = this._joystickPointerPos.clone();
  78256. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  78257. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  78258. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  78259. switch (this._axisTargetedByLeftAndRight) {
  78260. case JoystickAxis.X:
  78261. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  78262. break;
  78263. case JoystickAxis.Y:
  78264. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  78265. break;
  78266. case JoystickAxis.Z:
  78267. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  78268. break;
  78269. }
  78270. var directionUpDown = this.reverseUpDown ? 1 : -1;
  78271. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  78272. switch (this._axisTargetedByUpAndDown) {
  78273. case JoystickAxis.X:
  78274. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  78275. break;
  78276. case JoystickAxis.Y:
  78277. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  78278. break;
  78279. case JoystickAxis.Z:
  78280. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  78281. break;
  78282. }
  78283. }
  78284. else {
  78285. var data = this._touches.get(e.pointerId.toString());
  78286. if (data) {
  78287. data.x = e.clientX;
  78288. data.y = e.clientY;
  78289. }
  78290. }
  78291. };
  78292. VirtualJoystick.prototype._onPointerUp = function (e) {
  78293. if (this._joystickPointerID == e.pointerId) {
  78294. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  78295. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  78296. this._joystickPointerID = -1;
  78297. this.pressed = false;
  78298. }
  78299. else {
  78300. var touch = this._touches.get(e.pointerId.toString());
  78301. if (touch) {
  78302. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78303. }
  78304. }
  78305. this._deltaJoystickVector.x = 0;
  78306. this._deltaJoystickVector.y = 0;
  78307. this._touches.remove(e.pointerId.toString());
  78308. };
  78309. /**
  78310. * Change the color of the virtual joystick
  78311. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  78312. */
  78313. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  78314. this._joystickColor = newColor;
  78315. };
  78316. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  78317. this._action = action;
  78318. };
  78319. // Define which axis you'd like to control for left & right
  78320. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  78321. switch (axis) {
  78322. case JoystickAxis.X:
  78323. case JoystickAxis.Y:
  78324. case JoystickAxis.Z:
  78325. this._axisTargetedByLeftAndRight = axis;
  78326. break;
  78327. default:
  78328. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78329. break;
  78330. }
  78331. };
  78332. // Define which axis you'd like to control for up & down
  78333. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  78334. switch (axis) {
  78335. case JoystickAxis.X:
  78336. case JoystickAxis.Y:
  78337. case JoystickAxis.Z:
  78338. this._axisTargetedByUpAndDown = axis;
  78339. break;
  78340. default:
  78341. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78342. break;
  78343. }
  78344. };
  78345. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  78346. var _this = this;
  78347. if (this.pressed) {
  78348. this._touches.forEach(function (key, touch) {
  78349. if (touch.pointerId === _this._joystickPointerID) {
  78350. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  78351. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  78352. VirtualJoystick.vjCanvasContext.beginPath();
  78353. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78354. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78355. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  78356. VirtualJoystick.vjCanvasContext.stroke();
  78357. VirtualJoystick.vjCanvasContext.closePath();
  78358. VirtualJoystick.vjCanvasContext.beginPath();
  78359. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78360. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78361. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  78362. VirtualJoystick.vjCanvasContext.stroke();
  78363. VirtualJoystick.vjCanvasContext.closePath();
  78364. VirtualJoystick.vjCanvasContext.beginPath();
  78365. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78366. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  78367. VirtualJoystick.vjCanvasContext.stroke();
  78368. VirtualJoystick.vjCanvasContext.closePath();
  78369. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  78370. }
  78371. else {
  78372. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78373. VirtualJoystick.vjCanvasContext.beginPath();
  78374. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  78375. VirtualJoystick.vjCanvasContext.beginPath();
  78376. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  78377. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78378. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  78379. VirtualJoystick.vjCanvasContext.stroke();
  78380. VirtualJoystick.vjCanvasContext.closePath();
  78381. touch.prevX = touch.x;
  78382. touch.prevY = touch.y;
  78383. }
  78384. ;
  78385. });
  78386. }
  78387. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78388. };
  78389. VirtualJoystick.prototype.releaseCanvas = function () {
  78390. if (VirtualJoystick.vjCanvas) {
  78391. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  78392. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  78393. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  78394. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  78395. window.removeEventListener("resize", this._onResize);
  78396. document.body.removeChild(VirtualJoystick.vjCanvas);
  78397. VirtualJoystick.vjCanvas = null;
  78398. }
  78399. };
  78400. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  78401. VirtualJoystick._globalJoystickIndex = 0;
  78402. return VirtualJoystick;
  78403. }());
  78404. BABYLON.VirtualJoystick = VirtualJoystick;
  78405. })(BABYLON || (BABYLON = {}));
  78406. //# sourceMappingURL=babylon.virtualJoystick.js.map
  78407. var BABYLON;
  78408. (function (BABYLON) {
  78409. // We're mainly based on the logic defined into the FreeCamera code
  78410. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  78411. __extends(VirtualJoysticksCamera, _super);
  78412. function VirtualJoysticksCamera(name, position, scene) {
  78413. var _this = _super.call(this, name, position, scene) || this;
  78414. _this.inputs.addVirtualJoystick();
  78415. return _this;
  78416. }
  78417. VirtualJoysticksCamera.prototype.getClassName = function () {
  78418. return "VirtualJoysticksCamera";
  78419. };
  78420. return VirtualJoysticksCamera;
  78421. }(BABYLON.FreeCamera));
  78422. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  78423. })(BABYLON || (BABYLON = {}));
  78424. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  78425. var BABYLON;
  78426. (function (BABYLON) {
  78427. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  78428. function FreeCameraVirtualJoystickInput() {
  78429. }
  78430. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  78431. return this._leftjoystick;
  78432. };
  78433. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  78434. return this._rightjoystick;
  78435. };
  78436. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  78437. if (this._leftjoystick) {
  78438. var camera = this.camera;
  78439. var speed = camera._computeLocalCameraSpeed() * 50;
  78440. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  78441. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  78442. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  78443. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  78444. if (!this._leftjoystick.pressed) {
  78445. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  78446. }
  78447. if (!this._rightjoystick.pressed) {
  78448. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  78449. }
  78450. }
  78451. };
  78452. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  78453. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  78454. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  78455. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78456. this._leftjoystick.setJoystickSensibility(0.15);
  78457. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78458. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78459. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78460. this._rightjoystick.reverseUpDown = true;
  78461. this._rightjoystick.setJoystickSensibility(0.05);
  78462. this._rightjoystick.setJoystickColor("yellow");
  78463. };
  78464. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78465. this._leftjoystick.releaseCanvas();
  78466. this._rightjoystick.releaseCanvas();
  78467. };
  78468. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78469. return "FreeCameraVirtualJoystickInput";
  78470. };
  78471. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78472. return "virtualJoystick";
  78473. };
  78474. return FreeCameraVirtualJoystickInput;
  78475. }());
  78476. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78477. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78478. })(BABYLON || (BABYLON = {}));
  78479. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78480. var BABYLON;
  78481. (function (BABYLON) {
  78482. var SimplificationSettings = /** @class */ (function () {
  78483. function SimplificationSettings(quality, distance, optimizeMesh) {
  78484. this.quality = quality;
  78485. this.distance = distance;
  78486. this.optimizeMesh = optimizeMesh;
  78487. }
  78488. return SimplificationSettings;
  78489. }());
  78490. BABYLON.SimplificationSettings = SimplificationSettings;
  78491. var SimplificationQueue = /** @class */ (function () {
  78492. function SimplificationQueue() {
  78493. this.running = false;
  78494. this._simplificationArray = [];
  78495. }
  78496. SimplificationQueue.prototype.addTask = function (task) {
  78497. this._simplificationArray.push(task);
  78498. };
  78499. SimplificationQueue.prototype.executeNext = function () {
  78500. var task = this._simplificationArray.pop();
  78501. if (task) {
  78502. this.running = true;
  78503. this.runSimplification(task);
  78504. }
  78505. else {
  78506. this.running = false;
  78507. }
  78508. };
  78509. SimplificationQueue.prototype.runSimplification = function (task) {
  78510. var _this = this;
  78511. if (task.parallelProcessing) {
  78512. //parallel simplifier
  78513. task.settings.forEach(function (setting) {
  78514. var simplifier = _this.getSimplifier(task);
  78515. simplifier.simplify(setting, function (newMesh) {
  78516. task.mesh.addLODLevel(setting.distance, newMesh);
  78517. newMesh.isVisible = true;
  78518. //check if it is the last
  78519. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78520. //all done, run the success callback.
  78521. task.successCallback();
  78522. }
  78523. _this.executeNext();
  78524. });
  78525. });
  78526. }
  78527. else {
  78528. //single simplifier.
  78529. var simplifier = this.getSimplifier(task);
  78530. var runDecimation = function (setting, callback) {
  78531. simplifier.simplify(setting, function (newMesh) {
  78532. task.mesh.addLODLevel(setting.distance, newMesh);
  78533. newMesh.isVisible = true;
  78534. //run the next quality level
  78535. callback();
  78536. });
  78537. };
  78538. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78539. runDecimation(task.settings[loop.index], function () {
  78540. loop.executeNext();
  78541. });
  78542. }, function () {
  78543. //execution ended, run the success callback.
  78544. if (task.successCallback) {
  78545. task.successCallback();
  78546. }
  78547. _this.executeNext();
  78548. });
  78549. }
  78550. };
  78551. SimplificationQueue.prototype.getSimplifier = function (task) {
  78552. switch (task.simplificationType) {
  78553. case SimplificationType.QUADRATIC:
  78554. default:
  78555. return new QuadraticErrorSimplification(task.mesh);
  78556. }
  78557. };
  78558. return SimplificationQueue;
  78559. }());
  78560. BABYLON.SimplificationQueue = SimplificationQueue;
  78561. /**
  78562. * The implemented types of simplification.
  78563. * At the moment only Quadratic Error Decimation is implemented.
  78564. */
  78565. var SimplificationType;
  78566. (function (SimplificationType) {
  78567. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78568. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78569. var DecimationTriangle = /** @class */ (function () {
  78570. function DecimationTriangle(vertices) {
  78571. this.vertices = vertices;
  78572. this.error = new Array(4);
  78573. this.deleted = false;
  78574. this.isDirty = false;
  78575. this.deletePending = false;
  78576. this.borderFactor = 0;
  78577. }
  78578. return DecimationTriangle;
  78579. }());
  78580. BABYLON.DecimationTriangle = DecimationTriangle;
  78581. var DecimationVertex = /** @class */ (function () {
  78582. function DecimationVertex(position, id) {
  78583. this.position = position;
  78584. this.id = id;
  78585. this.isBorder = true;
  78586. this.q = new QuadraticMatrix();
  78587. this.triangleCount = 0;
  78588. this.triangleStart = 0;
  78589. this.originalOffsets = [];
  78590. }
  78591. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78592. this.position.copyFrom(newPosition);
  78593. };
  78594. return DecimationVertex;
  78595. }());
  78596. BABYLON.DecimationVertex = DecimationVertex;
  78597. var QuadraticMatrix = /** @class */ (function () {
  78598. function QuadraticMatrix(data) {
  78599. this.data = new Array(10);
  78600. for (var i = 0; i < 10; ++i) {
  78601. if (data && data[i]) {
  78602. this.data[i] = data[i];
  78603. }
  78604. else {
  78605. this.data[i] = 0;
  78606. }
  78607. }
  78608. }
  78609. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78610. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78611. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78612. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78613. return det;
  78614. };
  78615. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78616. for (var i = 0; i < 10; ++i) {
  78617. this.data[i] += matrix.data[i];
  78618. }
  78619. };
  78620. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78621. for (var i = 0; i < 10; ++i) {
  78622. this.data[i] += data[i];
  78623. }
  78624. };
  78625. QuadraticMatrix.prototype.add = function (matrix) {
  78626. var m = new QuadraticMatrix();
  78627. for (var i = 0; i < 10; ++i) {
  78628. m.data[i] = this.data[i] + matrix.data[i];
  78629. }
  78630. return m;
  78631. };
  78632. QuadraticMatrix.FromData = function (a, b, c, d) {
  78633. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78634. };
  78635. //returning an array to avoid garbage collection
  78636. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78637. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78638. };
  78639. return QuadraticMatrix;
  78640. }());
  78641. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78642. var Reference = /** @class */ (function () {
  78643. function Reference(vertexId, triangleId) {
  78644. this.vertexId = vertexId;
  78645. this.triangleId = triangleId;
  78646. }
  78647. return Reference;
  78648. }());
  78649. BABYLON.Reference = Reference;
  78650. /**
  78651. * An implementation of the Quadratic Error simplification algorithm.
  78652. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78653. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78654. * @author RaananW
  78655. */
  78656. var QuadraticErrorSimplification = /** @class */ (function () {
  78657. function QuadraticErrorSimplification(_mesh) {
  78658. this._mesh = _mesh;
  78659. this.syncIterations = 5000;
  78660. this.aggressiveness = 7;
  78661. this.decimationIterations = 100;
  78662. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78663. }
  78664. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78665. var _this = this;
  78666. this.initDecimatedMesh();
  78667. //iterating through the submeshes array, one after the other.
  78668. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78669. _this.initWithMesh(loop.index, function () {
  78670. _this.runDecimation(settings, loop.index, function () {
  78671. loop.executeNext();
  78672. });
  78673. }, settings.optimizeMesh);
  78674. }, function () {
  78675. setTimeout(function () {
  78676. successCallback(_this._reconstructedMesh);
  78677. }, 0);
  78678. });
  78679. };
  78680. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78681. var _this = this;
  78682. var targetCount = ~~(this.triangles.length * settings.quality);
  78683. var deletedTriangles = 0;
  78684. var triangleCount = this.triangles.length;
  78685. var iterationFunction = function (iteration, callback) {
  78686. setTimeout(function () {
  78687. if (iteration % 5 === 0) {
  78688. _this.updateMesh(iteration === 0);
  78689. }
  78690. for (var i = 0; i < _this.triangles.length; ++i) {
  78691. _this.triangles[i].isDirty = false;
  78692. }
  78693. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78694. var trianglesIterator = function (i) {
  78695. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78696. var t = _this.triangles[tIdx];
  78697. if (!t)
  78698. return;
  78699. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78700. return;
  78701. }
  78702. for (var j = 0; j < 3; ++j) {
  78703. if (t.error[j] < threshold) {
  78704. var deleted0 = [];
  78705. var deleted1 = [];
  78706. var v0 = t.vertices[j];
  78707. var v1 = t.vertices[(j + 1) % 3];
  78708. if (v0.isBorder || v1.isBorder)
  78709. continue;
  78710. var p = BABYLON.Vector3.Zero();
  78711. var n = BABYLON.Vector3.Zero();
  78712. var uv = BABYLON.Vector2.Zero();
  78713. var color = new BABYLON.Color4(0, 0, 0, 1);
  78714. _this.calculateError(v0, v1, p, n, uv, color);
  78715. var delTr = new Array();
  78716. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78717. continue;
  78718. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78719. continue;
  78720. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78721. continue;
  78722. var uniqueArray = new Array();
  78723. delTr.forEach(function (deletedT) {
  78724. if (uniqueArray.indexOf(deletedT) === -1) {
  78725. deletedT.deletePending = true;
  78726. uniqueArray.push(deletedT);
  78727. }
  78728. });
  78729. if (uniqueArray.length % 2 !== 0) {
  78730. continue;
  78731. }
  78732. v0.q = v1.q.add(v0.q);
  78733. v0.updatePosition(p);
  78734. var tStart = _this.references.length;
  78735. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78736. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78737. var tCount = _this.references.length - tStart;
  78738. if (tCount <= v0.triangleCount) {
  78739. if (tCount) {
  78740. for (var c = 0; c < tCount; c++) {
  78741. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78742. }
  78743. }
  78744. }
  78745. else {
  78746. v0.triangleStart = tStart;
  78747. }
  78748. v0.triangleCount = tCount;
  78749. break;
  78750. }
  78751. }
  78752. };
  78753. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78754. }, 0);
  78755. };
  78756. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78757. if (triangleCount - deletedTriangles <= targetCount)
  78758. loop.breakLoop();
  78759. else {
  78760. iterationFunction(loop.index, function () {
  78761. loop.executeNext();
  78762. });
  78763. }
  78764. }, function () {
  78765. setTimeout(function () {
  78766. //reconstruct this part of the mesh
  78767. _this.reconstructMesh(submeshIndex);
  78768. successCallback();
  78769. }, 0);
  78770. });
  78771. };
  78772. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  78773. var _this = this;
  78774. this.vertices = [];
  78775. this.triangles = [];
  78776. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78777. var indices = this._mesh.getIndices();
  78778. var submesh = this._mesh.subMeshes[submeshIndex];
  78779. var findInVertices = function (positionToSearch) {
  78780. if (optimizeMesh) {
  78781. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  78782. if (_this.vertices[ii].position.equals(positionToSearch)) {
  78783. return _this.vertices[ii];
  78784. }
  78785. }
  78786. }
  78787. return null;
  78788. };
  78789. var vertexReferences = [];
  78790. var vertexInit = function (i) {
  78791. if (!positionData) {
  78792. return;
  78793. }
  78794. var offset = i + submesh.verticesStart;
  78795. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  78796. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  78797. vertex.originalOffsets.push(offset);
  78798. if (vertex.id === _this.vertices.length) {
  78799. _this.vertices.push(vertex);
  78800. }
  78801. vertexReferences.push(vertex.id);
  78802. };
  78803. //var totalVertices = mesh.getTotalVertices();
  78804. var totalVertices = submesh.verticesCount;
  78805. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  78806. var indicesInit = function (i) {
  78807. if (!indices) {
  78808. return;
  78809. }
  78810. var offset = (submesh.indexStart / 3) + i;
  78811. var pos = (offset * 3);
  78812. var i0 = indices[pos + 0];
  78813. var i1 = indices[pos + 1];
  78814. var i2 = indices[pos + 2];
  78815. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  78816. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  78817. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  78818. var triangle = new DecimationTriangle([v0, v1, v2]);
  78819. triangle.originalOffset = pos;
  78820. _this.triangles.push(triangle);
  78821. };
  78822. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  78823. _this.init(callback);
  78824. });
  78825. });
  78826. };
  78827. QuadraticErrorSimplification.prototype.init = function (callback) {
  78828. var _this = this;
  78829. var triangleInit1 = function (i) {
  78830. var t = _this.triangles[i];
  78831. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  78832. for (var j = 0; j < 3; j++) {
  78833. 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))));
  78834. }
  78835. };
  78836. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  78837. var triangleInit2 = function (i) {
  78838. var t = _this.triangles[i];
  78839. for (var j = 0; j < 3; ++j) {
  78840. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  78841. }
  78842. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78843. };
  78844. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  78845. callback();
  78846. });
  78847. });
  78848. };
  78849. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  78850. var newTriangles = [];
  78851. var i;
  78852. for (i = 0; i < this.vertices.length; ++i) {
  78853. this.vertices[i].triangleCount = 0;
  78854. }
  78855. var t;
  78856. var j;
  78857. for (i = 0; i < this.triangles.length; ++i) {
  78858. if (!this.triangles[i].deleted) {
  78859. t = this.triangles[i];
  78860. for (j = 0; j < 3; ++j) {
  78861. t.vertices[j].triangleCount = 1;
  78862. }
  78863. newTriangles.push(t);
  78864. }
  78865. }
  78866. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  78867. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  78868. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  78869. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  78870. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  78871. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78872. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  78873. var vertexCount = 0;
  78874. for (i = 0; i < this.vertices.length; ++i) {
  78875. var vertex = this.vertices[i];
  78876. vertex.id = vertexCount;
  78877. if (vertex.triangleCount) {
  78878. vertex.originalOffsets.forEach(function (originalOffset) {
  78879. if (!normalData) {
  78880. return;
  78881. }
  78882. newPositionData.push(vertex.position.x);
  78883. newPositionData.push(vertex.position.y);
  78884. newPositionData.push(vertex.position.z);
  78885. newNormalData.push(normalData[originalOffset * 3]);
  78886. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  78887. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  78888. if (uvs && uvs.length) {
  78889. newUVsData.push(uvs[(originalOffset * 2)]);
  78890. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  78891. }
  78892. else if (colorsData && colorsData.length) {
  78893. newColorsData.push(colorsData[(originalOffset * 4)]);
  78894. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  78895. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  78896. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  78897. }
  78898. ++vertexCount;
  78899. });
  78900. }
  78901. }
  78902. var startingIndex = this._reconstructedMesh.getTotalIndices();
  78903. var startingVertex = this._reconstructedMesh.getTotalVertices();
  78904. var submeshesArray = this._reconstructedMesh.subMeshes;
  78905. this._reconstructedMesh.subMeshes = [];
  78906. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  78907. var originalIndices = this._mesh.getIndices();
  78908. for (i = 0; i < newTriangles.length; ++i) {
  78909. t = newTriangles[i]; //now get the new referencing point for each vertex
  78910. [0, 1, 2].forEach(function (idx) {
  78911. var id = originalIndices[t.originalOffset + idx];
  78912. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  78913. if (offset < 0)
  78914. offset = 0;
  78915. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  78916. });
  78917. }
  78918. //overwriting the old vertex buffers and indices.
  78919. this._reconstructedMesh.setIndices(newIndicesArray);
  78920. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  78921. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  78922. if (newUVsData.length > 0)
  78923. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  78924. if (newColorsData.length > 0)
  78925. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  78926. //create submesh
  78927. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  78928. if (submeshIndex > 0) {
  78929. this._reconstructedMesh.subMeshes = [];
  78930. submeshesArray.forEach(function (submesh) {
  78931. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  78932. });
  78933. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  78934. }
  78935. };
  78936. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  78937. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  78938. this._reconstructedMesh.material = this._mesh.material;
  78939. this._reconstructedMesh.parent = this._mesh.parent;
  78940. this._reconstructedMesh.isVisible = false;
  78941. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  78942. };
  78943. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  78944. for (var i = 0; i < vertex1.triangleCount; ++i) {
  78945. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  78946. if (t.deleted)
  78947. continue;
  78948. var s = this.references[vertex1.triangleStart + i].vertexId;
  78949. var v1 = t.vertices[(s + 1) % 3];
  78950. var v2 = t.vertices[(s + 2) % 3];
  78951. if ((v1 === vertex2 || v2 === vertex2)) {
  78952. deletedArray[i] = true;
  78953. delTr.push(t);
  78954. continue;
  78955. }
  78956. var d1 = v1.position.subtract(point);
  78957. d1 = d1.normalize();
  78958. var d2 = v2.position.subtract(point);
  78959. d2 = d2.normalize();
  78960. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  78961. return true;
  78962. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  78963. deletedArray[i] = false;
  78964. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  78965. return true;
  78966. }
  78967. return false;
  78968. };
  78969. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  78970. var newDeleted = deletedTriangles;
  78971. for (var i = 0; i < vertex.triangleCount; ++i) {
  78972. var ref = this.references[vertex.triangleStart + i];
  78973. var t = this.triangles[ref.triangleId];
  78974. if (t.deleted)
  78975. continue;
  78976. if (deletedArray[i] && t.deletePending) {
  78977. t.deleted = true;
  78978. newDeleted++;
  78979. continue;
  78980. }
  78981. t.vertices[ref.vertexId] = origVertex;
  78982. t.isDirty = true;
  78983. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  78984. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  78985. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  78986. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78987. this.references.push(ref);
  78988. }
  78989. return newDeleted;
  78990. };
  78991. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  78992. for (var i = 0; i < this.vertices.length; ++i) {
  78993. var vCount = [];
  78994. var vId = [];
  78995. var v = this.vertices[i];
  78996. var j;
  78997. for (j = 0; j < v.triangleCount; ++j) {
  78998. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  78999. for (var ii = 0; ii < 3; ii++) {
  79000. var ofs = 0;
  79001. var vv = triangle.vertices[ii];
  79002. while (ofs < vCount.length) {
  79003. if (vId[ofs] === vv.id)
  79004. break;
  79005. ++ofs;
  79006. }
  79007. if (ofs === vCount.length) {
  79008. vCount.push(1);
  79009. vId.push(vv.id);
  79010. }
  79011. else {
  79012. vCount[ofs]++;
  79013. }
  79014. }
  79015. }
  79016. for (j = 0; j < vCount.length; ++j) {
  79017. if (vCount[j] === 1) {
  79018. this.vertices[vId[j]].isBorder = true;
  79019. }
  79020. else {
  79021. this.vertices[vId[j]].isBorder = false;
  79022. }
  79023. }
  79024. }
  79025. };
  79026. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  79027. if (identifyBorders === void 0) { identifyBorders = false; }
  79028. var i;
  79029. if (!identifyBorders) {
  79030. var newTrianglesVector = [];
  79031. for (i = 0; i < this.triangles.length; ++i) {
  79032. if (!this.triangles[i].deleted) {
  79033. newTrianglesVector.push(this.triangles[i]);
  79034. }
  79035. }
  79036. this.triangles = newTrianglesVector;
  79037. }
  79038. for (i = 0; i < this.vertices.length; ++i) {
  79039. this.vertices[i].triangleCount = 0;
  79040. this.vertices[i].triangleStart = 0;
  79041. }
  79042. var t;
  79043. var j;
  79044. var v;
  79045. for (i = 0; i < this.triangles.length; ++i) {
  79046. t = this.triangles[i];
  79047. for (j = 0; j < 3; ++j) {
  79048. v = t.vertices[j];
  79049. v.triangleCount++;
  79050. }
  79051. }
  79052. var tStart = 0;
  79053. for (i = 0; i < this.vertices.length; ++i) {
  79054. this.vertices[i].triangleStart = tStart;
  79055. tStart += this.vertices[i].triangleCount;
  79056. this.vertices[i].triangleCount = 0;
  79057. }
  79058. var newReferences = new Array(this.triangles.length * 3);
  79059. for (i = 0; i < this.triangles.length; ++i) {
  79060. t = this.triangles[i];
  79061. for (j = 0; j < 3; ++j) {
  79062. v = t.vertices[j];
  79063. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  79064. v.triangleCount++;
  79065. }
  79066. }
  79067. this.references = newReferences;
  79068. if (identifyBorders) {
  79069. this.identifyBorder();
  79070. }
  79071. };
  79072. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  79073. var x = point.x;
  79074. var y = point.y;
  79075. var z = point.z;
  79076. 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
  79077. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  79078. };
  79079. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  79080. var q = vertex1.q.add(vertex2.q);
  79081. var border = vertex1.isBorder && vertex2.isBorder;
  79082. var error = 0;
  79083. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  79084. if (qDet !== 0 && !border) {
  79085. if (!pointResult) {
  79086. pointResult = BABYLON.Vector3.Zero();
  79087. }
  79088. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  79089. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  79090. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  79091. error = this.vertexError(q, pointResult);
  79092. }
  79093. else {
  79094. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  79095. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  79096. var error1 = this.vertexError(q, vertex1.position);
  79097. var error2 = this.vertexError(q, vertex2.position);
  79098. var error3 = this.vertexError(q, p3);
  79099. error = Math.min(error1, error2, error3);
  79100. if (error === error1) {
  79101. if (pointResult) {
  79102. pointResult.copyFrom(vertex1.position);
  79103. }
  79104. }
  79105. else if (error === error2) {
  79106. if (pointResult) {
  79107. pointResult.copyFrom(vertex2.position);
  79108. }
  79109. }
  79110. else {
  79111. if (pointResult) {
  79112. pointResult.copyFrom(p3);
  79113. }
  79114. }
  79115. }
  79116. return error;
  79117. };
  79118. return QuadraticErrorSimplification;
  79119. }());
  79120. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  79121. })(BABYLON || (BABYLON = {}));
  79122. //# sourceMappingURL=babylon.meshSimplification.js.map
  79123. var BABYLON;
  79124. (function (BABYLON) {
  79125. var MeshLODLevel = /** @class */ (function () {
  79126. function MeshLODLevel(distance, mesh) {
  79127. this.distance = distance;
  79128. this.mesh = mesh;
  79129. }
  79130. return MeshLODLevel;
  79131. }());
  79132. BABYLON.MeshLODLevel = MeshLODLevel;
  79133. })(BABYLON || (BABYLON = {}));
  79134. //# sourceMappingURL=babylon.meshLODLevel.js.map
  79135. var BABYLON;
  79136. (function (BABYLON) {
  79137. /**
  79138. * Defines the root class used to create scene optimization to use with SceneOptimizer
  79139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79140. */
  79141. var SceneOptimization = /** @class */ (function () {
  79142. /**
  79143. * Creates the SceneOptimization object
  79144. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79145. * @param desc defines the description associated with the optimization
  79146. */
  79147. function SceneOptimization(
  79148. /**
  79149. * Defines the priority of this optimization (0 by default which means first in the list)
  79150. */
  79151. priority) {
  79152. if (priority === void 0) { priority = 0; }
  79153. this.priority = priority;
  79154. }
  79155. /**
  79156. * Gets a string describing the action executed by the current optimization
  79157. * @returns description string
  79158. */
  79159. SceneOptimization.prototype.getDescription = function () {
  79160. return "";
  79161. };
  79162. /**
  79163. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79164. * @param scene defines the current scene where to apply this optimization
  79165. * @param optimizer defines the current optimizer
  79166. * @returns true if everything that can be done was applied
  79167. */
  79168. SceneOptimization.prototype.apply = function (scene, optimizer) {
  79169. return true;
  79170. };
  79171. ;
  79172. return SceneOptimization;
  79173. }());
  79174. BABYLON.SceneOptimization = SceneOptimization;
  79175. /**
  79176. * Defines an optimization used to reduce the size of render target textures
  79177. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79178. */
  79179. var TextureOptimization = /** @class */ (function (_super) {
  79180. __extends(TextureOptimization, _super);
  79181. /**
  79182. * Creates the TextureOptimization object
  79183. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79184. * @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
  79185. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79186. */
  79187. function TextureOptimization(
  79188. /**
  79189. * Defines the priority of this optimization (0 by default which means first in the list)
  79190. */
  79191. priority,
  79192. /**
  79193. * 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
  79194. */
  79195. maximumSize,
  79196. /**
  79197. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79198. */
  79199. step) {
  79200. if (priority === void 0) { priority = 0; }
  79201. if (maximumSize === void 0) { maximumSize = 1024; }
  79202. if (step === void 0) { step = 0.5; }
  79203. var _this = _super.call(this, priority) || this;
  79204. _this.priority = priority;
  79205. _this.maximumSize = maximumSize;
  79206. _this.step = step;
  79207. return _this;
  79208. }
  79209. /**
  79210. * Gets a string describing the action executed by the current optimization
  79211. * @returns description string
  79212. */
  79213. TextureOptimization.prototype.getDescription = function () {
  79214. return "Reducing render target texture size to " + this.maximumSize;
  79215. };
  79216. /**
  79217. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79218. * @param scene defines the current scene where to apply this optimization
  79219. * @param optimizer defines the current optimizer
  79220. * @returns true if everything that can be done was applied
  79221. */
  79222. TextureOptimization.prototype.apply = function (scene, optimizer) {
  79223. var allDone = true;
  79224. for (var index = 0; index < scene.textures.length; index++) {
  79225. var texture = scene.textures[index];
  79226. if (!texture.canRescale || texture.getContext) {
  79227. continue;
  79228. }
  79229. var currentSize = texture.getSize();
  79230. var maxDimension = Math.max(currentSize.width, currentSize.height);
  79231. if (maxDimension > this.maximumSize) {
  79232. texture.scale(this.step);
  79233. allDone = false;
  79234. }
  79235. }
  79236. return allDone;
  79237. };
  79238. return TextureOptimization;
  79239. }(SceneOptimization));
  79240. BABYLON.TextureOptimization = TextureOptimization;
  79241. /**
  79242. * Defines an optimization used to increase or decrease the rendering resolution
  79243. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79244. */
  79245. var HardwareScalingOptimization = /** @class */ (function (_super) {
  79246. __extends(HardwareScalingOptimization, _super);
  79247. /**
  79248. * Creates the HardwareScalingOptimization object
  79249. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79250. * @param maximumScale defines the maximum scale to use (2 by default)
  79251. * @param step defines the step to use between two passes (0.5 by default)
  79252. */
  79253. function HardwareScalingOptimization(
  79254. /**
  79255. * Defines the priority of this optimization (0 by default which means first in the list)
  79256. */
  79257. priority,
  79258. /**
  79259. * Defines the maximum scale to use (2 by default)
  79260. */
  79261. maximumScale,
  79262. /**
  79263. * Defines the step to use between two passes (0.5 by default)
  79264. */
  79265. step) {
  79266. if (priority === void 0) { priority = 0; }
  79267. if (maximumScale === void 0) { maximumScale = 2; }
  79268. if (step === void 0) { step = 0.25; }
  79269. var _this = _super.call(this, priority) || this;
  79270. _this.priority = priority;
  79271. _this.maximumScale = maximumScale;
  79272. _this.step = step;
  79273. _this._currentScale = -1;
  79274. _this._directionOffset = 1;
  79275. return _this;
  79276. }
  79277. /**
  79278. * Gets a string describing the action executed by the current optimization
  79279. * @return description string
  79280. */
  79281. HardwareScalingOptimization.prototype.getDescription = function () {
  79282. return "Setting hardware scaling level to " + this._currentScale;
  79283. };
  79284. /**
  79285. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79286. * @param scene defines the current scene where to apply this optimization
  79287. * @param optimizer defines the current optimizer
  79288. * @returns true if everything that can be done was applied
  79289. */
  79290. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  79291. if (this._currentScale === -1) {
  79292. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  79293. if (this._currentScale > this.maximumScale) {
  79294. this._directionOffset = -1;
  79295. }
  79296. }
  79297. this._currentScale += this._directionOffset * this.step;
  79298. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  79299. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  79300. };
  79301. ;
  79302. return HardwareScalingOptimization;
  79303. }(SceneOptimization));
  79304. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  79305. /**
  79306. * Defines an optimization used to remove shadows
  79307. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79308. */
  79309. var ShadowsOptimization = /** @class */ (function (_super) {
  79310. __extends(ShadowsOptimization, _super);
  79311. function ShadowsOptimization() {
  79312. return _super !== null && _super.apply(this, arguments) || this;
  79313. }
  79314. /**
  79315. * Gets a string describing the action executed by the current optimization
  79316. * @return description string
  79317. */
  79318. ShadowsOptimization.prototype.getDescription = function () {
  79319. return "Turning shadows on/off";
  79320. };
  79321. /**
  79322. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79323. * @param scene defines the current scene where to apply this optimization
  79324. * @param optimizer defines the current optimizer
  79325. * @returns true if everything that can be done was applied
  79326. */
  79327. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  79328. scene.shadowsEnabled = optimizer.isInImprovementMode;
  79329. return true;
  79330. };
  79331. ;
  79332. return ShadowsOptimization;
  79333. }(SceneOptimization));
  79334. BABYLON.ShadowsOptimization = ShadowsOptimization;
  79335. /**
  79336. * Defines an optimization used to turn post-processes off
  79337. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79338. */
  79339. var PostProcessesOptimization = /** @class */ (function (_super) {
  79340. __extends(PostProcessesOptimization, _super);
  79341. function PostProcessesOptimization() {
  79342. return _super !== null && _super.apply(this, arguments) || this;
  79343. }
  79344. /**
  79345. * Gets a string describing the action executed by the current optimization
  79346. * @return description string
  79347. */
  79348. PostProcessesOptimization.prototype.getDescription = function () {
  79349. return "Turning post-processes on/off";
  79350. };
  79351. /**
  79352. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79353. * @param scene defines the current scene where to apply this optimization
  79354. * @param optimizer defines the current optimizer
  79355. * @returns true if everything that can be done was applied
  79356. */
  79357. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  79358. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  79359. return true;
  79360. };
  79361. ;
  79362. return PostProcessesOptimization;
  79363. }(SceneOptimization));
  79364. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  79365. /**
  79366. * Defines an optimization used to turn lens flares off
  79367. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79368. */
  79369. var LensFlaresOptimization = /** @class */ (function (_super) {
  79370. __extends(LensFlaresOptimization, _super);
  79371. function LensFlaresOptimization() {
  79372. return _super !== null && _super.apply(this, arguments) || this;
  79373. }
  79374. /**
  79375. * Gets a string describing the action executed by the current optimization
  79376. * @return description string
  79377. */
  79378. LensFlaresOptimization.prototype.getDescription = function () {
  79379. return "Turning lens flares on/off";
  79380. };
  79381. /**
  79382. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79383. * @param scene defines the current scene where to apply this optimization
  79384. * @param optimizer defines the current optimizer
  79385. * @returns true if everything that can be done was applied
  79386. */
  79387. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  79388. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  79389. return true;
  79390. };
  79391. ;
  79392. return LensFlaresOptimization;
  79393. }(SceneOptimization));
  79394. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  79395. /**
  79396. * Defines an optimization based on user defined callback.
  79397. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79398. */
  79399. var CustomOptimization = /** @class */ (function (_super) {
  79400. __extends(CustomOptimization, _super);
  79401. function CustomOptimization() {
  79402. return _super !== null && _super.apply(this, arguments) || this;
  79403. }
  79404. /**
  79405. * Gets a string describing the action executed by the current optimization
  79406. * @returns description string
  79407. */
  79408. CustomOptimization.prototype.getDescription = function () {
  79409. if (this.onGetDescription) {
  79410. return this.onGetDescription();
  79411. }
  79412. return "Running user defined callback";
  79413. };
  79414. /**
  79415. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79416. * @param scene defines the current scene where to apply this optimization
  79417. * @param optimizer defines the current optimizer
  79418. * @returns true if everything that can be done was applied
  79419. */
  79420. CustomOptimization.prototype.apply = function (scene, optimizer) {
  79421. if (this.onApply) {
  79422. return this.onApply(scene, optimizer);
  79423. }
  79424. return true;
  79425. };
  79426. ;
  79427. return CustomOptimization;
  79428. }(SceneOptimization));
  79429. BABYLON.CustomOptimization = CustomOptimization;
  79430. /**
  79431. * Defines an optimization used to turn particles off
  79432. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79433. */
  79434. var ParticlesOptimization = /** @class */ (function (_super) {
  79435. __extends(ParticlesOptimization, _super);
  79436. function ParticlesOptimization() {
  79437. return _super !== null && _super.apply(this, arguments) || this;
  79438. }
  79439. /**
  79440. * Gets a string describing the action executed by the current optimization
  79441. * @return description string
  79442. */
  79443. ParticlesOptimization.prototype.getDescription = function () {
  79444. return "Turning particles on/off";
  79445. };
  79446. /**
  79447. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79448. * @param scene defines the current scene where to apply this optimization
  79449. * @param optimizer defines the current optimizer
  79450. * @returns true if everything that can be done was applied
  79451. */
  79452. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  79453. scene.particlesEnabled = optimizer.isInImprovementMode;
  79454. return true;
  79455. };
  79456. ;
  79457. return ParticlesOptimization;
  79458. }(SceneOptimization));
  79459. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79460. /**
  79461. * Defines an optimization used to turn render targets off
  79462. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79463. */
  79464. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79465. __extends(RenderTargetsOptimization, _super);
  79466. function RenderTargetsOptimization() {
  79467. return _super !== null && _super.apply(this, arguments) || this;
  79468. }
  79469. /**
  79470. * Gets a string describing the action executed by the current optimization
  79471. * @return description string
  79472. */
  79473. RenderTargetsOptimization.prototype.getDescription = function () {
  79474. return "Turning render targets off";
  79475. };
  79476. /**
  79477. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79478. * @param scene defines the current scene where to apply this optimization
  79479. * @param optimizer defines the current optimizer
  79480. * @returns true if everything that can be done was applied
  79481. */
  79482. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79483. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79484. return true;
  79485. };
  79486. ;
  79487. return RenderTargetsOptimization;
  79488. }(SceneOptimization));
  79489. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79490. /**
  79491. * Defines an optimization used to merge meshes with compatible materials
  79492. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79493. */
  79494. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79495. __extends(MergeMeshesOptimization, _super);
  79496. function MergeMeshesOptimization() {
  79497. var _this = _super !== null && _super.apply(this, arguments) || this;
  79498. _this._canBeMerged = function (abstractMesh) {
  79499. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79500. return false;
  79501. }
  79502. var mesh = abstractMesh;
  79503. if (!mesh.isVisible || !mesh.isEnabled()) {
  79504. return false;
  79505. }
  79506. if (mesh.instances.length > 0) {
  79507. return false;
  79508. }
  79509. if (mesh.skeleton || mesh.hasLODLevels) {
  79510. return false;
  79511. }
  79512. if (mesh.parent) {
  79513. return false;
  79514. }
  79515. return true;
  79516. };
  79517. return _this;
  79518. }
  79519. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79520. /**
  79521. * Gets or sets a boolean which defines if optimization octree has to be updated
  79522. */
  79523. get: function () {
  79524. return MergeMeshesOptimization._UpdateSelectionTree;
  79525. },
  79526. /**
  79527. * Gets or sets a boolean which defines if optimization octree has to be updated
  79528. */
  79529. set: function (value) {
  79530. MergeMeshesOptimization._UpdateSelectionTree = value;
  79531. },
  79532. enumerable: true,
  79533. configurable: true
  79534. });
  79535. /**
  79536. * Gets a string describing the action executed by the current optimization
  79537. * @return description string
  79538. */
  79539. MergeMeshesOptimization.prototype.getDescription = function () {
  79540. return "Merging similar meshes together";
  79541. };
  79542. /**
  79543. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79544. * @param scene defines the current scene where to apply this optimization
  79545. * @param optimizer defines the current optimizer
  79546. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79547. * @returns true if everything that can be done was applied
  79548. */
  79549. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79550. var globalPool = scene.meshes.slice(0);
  79551. var globalLength = globalPool.length;
  79552. for (var index = 0; index < globalLength; index++) {
  79553. var currentPool = new Array();
  79554. var current = globalPool[index];
  79555. // Checks
  79556. if (!this._canBeMerged(current)) {
  79557. continue;
  79558. }
  79559. currentPool.push(current);
  79560. // Find compatible meshes
  79561. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79562. var otherMesh = globalPool[subIndex];
  79563. if (!this._canBeMerged(otherMesh)) {
  79564. continue;
  79565. }
  79566. if (otherMesh.material !== current.material) {
  79567. continue;
  79568. }
  79569. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79570. continue;
  79571. }
  79572. currentPool.push(otherMesh);
  79573. globalLength--;
  79574. globalPool.splice(subIndex, 1);
  79575. subIndex--;
  79576. }
  79577. if (currentPool.length < 2) {
  79578. continue;
  79579. }
  79580. // Merge meshes
  79581. BABYLON.Mesh.MergeMeshes(currentPool);
  79582. }
  79583. if (updateSelectionTree != undefined) {
  79584. if (updateSelectionTree) {
  79585. scene.createOrUpdateSelectionOctree();
  79586. }
  79587. }
  79588. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79589. scene.createOrUpdateSelectionOctree();
  79590. }
  79591. return true;
  79592. };
  79593. ;
  79594. MergeMeshesOptimization._UpdateSelectionTree = false;
  79595. return MergeMeshesOptimization;
  79596. }(SceneOptimization));
  79597. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79598. /**
  79599. * Defines a list of options used by SceneOptimizer
  79600. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79601. */
  79602. var SceneOptimizerOptions = /** @class */ (function () {
  79603. /**
  79604. * Creates a new list of options used by SceneOptimizer
  79605. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79606. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79607. */
  79608. function SceneOptimizerOptions(
  79609. /**
  79610. * Defines the target frame rate to reach (60 by default)
  79611. */
  79612. targetFrameRate,
  79613. /**
  79614. * Defines the interval between two checkes (2000ms by default)
  79615. */
  79616. trackerDuration) {
  79617. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79618. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79619. this.targetFrameRate = targetFrameRate;
  79620. this.trackerDuration = trackerDuration;
  79621. /**
  79622. * Gets the list of optimizations to apply
  79623. */
  79624. this.optimizations = new Array();
  79625. }
  79626. /**
  79627. * Add a new optimization
  79628. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79629. * @returns the current SceneOptimizerOptions
  79630. */
  79631. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79632. this.optimizations.push(optimization);
  79633. return this;
  79634. };
  79635. /**
  79636. * Add a new custom optimization
  79637. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79638. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79639. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79640. * @returns the current SceneOptimizerOptions
  79641. */
  79642. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79643. if (priority === void 0) { priority = 0; }
  79644. var optimization = new CustomOptimization(priority);
  79645. optimization.onApply = onApply;
  79646. optimization.onGetDescription = onGetDescription;
  79647. this.optimizations.push(optimization);
  79648. return this;
  79649. };
  79650. /**
  79651. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79652. * @param targetFrameRate defines the target frame rate (60 by default)
  79653. * @returns a SceneOptimizerOptions object
  79654. */
  79655. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79656. var result = new SceneOptimizerOptions(targetFrameRate);
  79657. var priority = 0;
  79658. result.addOptimization(new MergeMeshesOptimization(priority));
  79659. result.addOptimization(new ShadowsOptimization(priority));
  79660. result.addOptimization(new LensFlaresOptimization(priority));
  79661. // Next priority
  79662. priority++;
  79663. result.addOptimization(new PostProcessesOptimization(priority));
  79664. result.addOptimization(new ParticlesOptimization(priority));
  79665. // Next priority
  79666. priority++;
  79667. result.addOptimization(new TextureOptimization(priority, 1024));
  79668. return result;
  79669. };
  79670. /**
  79671. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79672. * @param targetFrameRate defines the target frame rate (60 by default)
  79673. * @returns a SceneOptimizerOptions object
  79674. */
  79675. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79676. var result = new SceneOptimizerOptions(targetFrameRate);
  79677. var priority = 0;
  79678. result.addOptimization(new MergeMeshesOptimization(priority));
  79679. result.addOptimization(new ShadowsOptimization(priority));
  79680. result.addOptimization(new LensFlaresOptimization(priority));
  79681. // Next priority
  79682. priority++;
  79683. result.addOptimization(new PostProcessesOptimization(priority));
  79684. result.addOptimization(new ParticlesOptimization(priority));
  79685. // Next priority
  79686. priority++;
  79687. result.addOptimization(new TextureOptimization(priority, 512));
  79688. // Next priority
  79689. priority++;
  79690. result.addOptimization(new RenderTargetsOptimization(priority));
  79691. // Next priority
  79692. priority++;
  79693. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79694. return result;
  79695. };
  79696. /**
  79697. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79698. * @param targetFrameRate defines the target frame rate (60 by default)
  79699. * @returns a SceneOptimizerOptions object
  79700. */
  79701. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79702. var result = new SceneOptimizerOptions(targetFrameRate);
  79703. var priority = 0;
  79704. result.addOptimization(new MergeMeshesOptimization(priority));
  79705. result.addOptimization(new ShadowsOptimization(priority));
  79706. result.addOptimization(new LensFlaresOptimization(priority));
  79707. // Next priority
  79708. priority++;
  79709. result.addOptimization(new PostProcessesOptimization(priority));
  79710. result.addOptimization(new ParticlesOptimization(priority));
  79711. // Next priority
  79712. priority++;
  79713. result.addOptimization(new TextureOptimization(priority, 256));
  79714. // Next priority
  79715. priority++;
  79716. result.addOptimization(new RenderTargetsOptimization(priority));
  79717. // Next priority
  79718. priority++;
  79719. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79720. return result;
  79721. };
  79722. return SceneOptimizerOptions;
  79723. }());
  79724. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79725. /**
  79726. * Class used to run optimizations in order to reach a target frame rate
  79727. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79728. */
  79729. var SceneOptimizer = /** @class */ (function () {
  79730. /**
  79731. * Creates a new SceneOptimizer
  79732. * @param scene defines the scene to work on
  79733. * @param options defines the options to use with the SceneOptimizer
  79734. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79735. * @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)
  79736. */
  79737. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79738. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79739. if (improvementMode === void 0) { improvementMode = false; }
  79740. var _this = this;
  79741. this._isRunning = false;
  79742. this._currentPriorityLevel = 0;
  79743. this._targetFrameRate = 60;
  79744. this._trackerDuration = 2000;
  79745. this._currentFrameRate = 0;
  79746. this._improvementMode = false;
  79747. /**
  79748. * Defines an observable called when the optimizer reaches the target frame rate
  79749. */
  79750. this.onSuccessObservable = new BABYLON.Observable();
  79751. /**
  79752. * Defines an observable called when the optimizer enables an optimization
  79753. */
  79754. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79755. /**
  79756. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79757. */
  79758. this.onFailureObservable = new BABYLON.Observable();
  79759. if (!options) {
  79760. this._options = new SceneOptimizerOptions();
  79761. }
  79762. else {
  79763. this._options = options;
  79764. }
  79765. if (this._options.targetFrameRate) {
  79766. this._targetFrameRate = this._options.targetFrameRate;
  79767. }
  79768. if (this._options.trackerDuration) {
  79769. this._trackerDuration = this._options.trackerDuration;
  79770. }
  79771. if (autoGeneratePriorities) {
  79772. var priority = 0;
  79773. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  79774. var optim = _a[_i];
  79775. optim.priority = priority++;
  79776. }
  79777. }
  79778. this._improvementMode = improvementMode;
  79779. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79780. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  79781. _this._sceneDisposeObserver = null;
  79782. _this.dispose();
  79783. });
  79784. }
  79785. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  79786. /**
  79787. * Gets a boolean indicating if the optimizer is in improvement mode
  79788. */
  79789. get: function () {
  79790. return this._improvementMode;
  79791. },
  79792. enumerable: true,
  79793. configurable: true
  79794. });
  79795. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  79796. /**
  79797. * Gets the current priority level (0 at start)
  79798. */
  79799. get: function () {
  79800. return this._currentPriorityLevel;
  79801. },
  79802. enumerable: true,
  79803. configurable: true
  79804. });
  79805. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  79806. /**
  79807. * Gets the current frame rate checked by the SceneOptimizer
  79808. */
  79809. get: function () {
  79810. return this._currentFrameRate;
  79811. },
  79812. enumerable: true,
  79813. configurable: true
  79814. });
  79815. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  79816. /**
  79817. * Gets or sets the current target frame rate (60 by default)
  79818. */
  79819. get: function () {
  79820. return this._targetFrameRate;
  79821. },
  79822. /**
  79823. * Gets or sets the current target frame rate (60 by default)
  79824. */
  79825. set: function (value) {
  79826. this._targetFrameRate = value;
  79827. },
  79828. enumerable: true,
  79829. configurable: true
  79830. });
  79831. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  79832. /**
  79833. * Gets or sets the current interval between two checks (every 2000ms by default)
  79834. */
  79835. get: function () {
  79836. return this._trackerDuration;
  79837. },
  79838. /**
  79839. * Gets or sets the current interval between two checks (every 2000ms by default)
  79840. */
  79841. set: function (value) {
  79842. this._trackerDuration = value;
  79843. },
  79844. enumerable: true,
  79845. configurable: true
  79846. });
  79847. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  79848. /**
  79849. * Gets the list of active optimizations
  79850. */
  79851. get: function () {
  79852. return this._options.optimizations;
  79853. },
  79854. enumerable: true,
  79855. configurable: true
  79856. });
  79857. /**
  79858. * Stops the current optimizer
  79859. */
  79860. SceneOptimizer.prototype.stop = function () {
  79861. this._isRunning = false;
  79862. };
  79863. /**
  79864. * Reset the optimizer to initial step (current priority level = 0)
  79865. */
  79866. SceneOptimizer.prototype.reset = function () {
  79867. this._currentPriorityLevel = 0;
  79868. };
  79869. /**
  79870. * Start the optimizer. By default it will try to reach a specific framerate
  79871. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  79872. */
  79873. SceneOptimizer.prototype.start = function () {
  79874. var _this = this;
  79875. if (this._isRunning) {
  79876. return;
  79877. }
  79878. this._isRunning = true;
  79879. // Let's wait for the scene to be ready before running our check
  79880. this._scene.executeWhenReady(function () {
  79881. setTimeout(function () {
  79882. _this._checkCurrentState();
  79883. }, _this._trackerDuration);
  79884. });
  79885. };
  79886. SceneOptimizer.prototype._checkCurrentState = function () {
  79887. var _this = this;
  79888. if (!this._isRunning) {
  79889. return;
  79890. }
  79891. var scene = this._scene;
  79892. var options = this._options;
  79893. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  79894. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  79895. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  79896. this._isRunning = false;
  79897. this.onSuccessObservable.notifyObservers(this);
  79898. return;
  79899. }
  79900. // Apply current level of optimizations
  79901. var allDone = true;
  79902. var noOptimizationApplied = true;
  79903. for (var index = 0; index < options.optimizations.length; index++) {
  79904. var optimization = options.optimizations[index];
  79905. if (optimization.priority === this._currentPriorityLevel) {
  79906. noOptimizationApplied = false;
  79907. allDone = allDone && optimization.apply(scene, this);
  79908. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  79909. }
  79910. }
  79911. // If no optimization was applied, this is a failure :(
  79912. if (noOptimizationApplied) {
  79913. this._isRunning = false;
  79914. this.onFailureObservable.notifyObservers(this);
  79915. return;
  79916. }
  79917. // If all optimizations were done, move to next level
  79918. if (allDone) {
  79919. this._currentPriorityLevel++;
  79920. }
  79921. // Let's the system running for a specific amount of time before checking FPS
  79922. scene.executeWhenReady(function () {
  79923. setTimeout(function () {
  79924. _this._checkCurrentState();
  79925. }, _this._trackerDuration);
  79926. });
  79927. };
  79928. /**
  79929. * Release all resources
  79930. */
  79931. SceneOptimizer.prototype.dispose = function () {
  79932. this.stop();
  79933. this.onSuccessObservable.clear();
  79934. this.onFailureObservable.clear();
  79935. this.onNewOptimizationAppliedObservable.clear();
  79936. if (this._sceneDisposeObserver) {
  79937. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  79938. }
  79939. };
  79940. /**
  79941. * Helper function to create a SceneOptimizer with one single line of code
  79942. * @param scene defines the scene to work on
  79943. * @param options defines the options to use with the SceneOptimizer
  79944. * @param onSuccess defines a callback to call on success
  79945. * @param onFailure defines a callback to call on failure
  79946. * @returns the new SceneOptimizer object
  79947. */
  79948. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  79949. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  79950. if (onSuccess) {
  79951. optimizer.onSuccessObservable.add(function () {
  79952. onSuccess();
  79953. });
  79954. }
  79955. if (onFailure) {
  79956. optimizer.onFailureObservable.add(function () {
  79957. onFailure();
  79958. });
  79959. }
  79960. optimizer.start();
  79961. return optimizer;
  79962. };
  79963. return SceneOptimizer;
  79964. }());
  79965. BABYLON.SceneOptimizer = SceneOptimizer;
  79966. })(BABYLON || (BABYLON = {}));
  79967. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  79968. var BABYLON;
  79969. (function (BABYLON) {
  79970. var OutlineRenderer = /** @class */ (function () {
  79971. function OutlineRenderer(scene) {
  79972. this.zOffset = 1;
  79973. this._scene = scene;
  79974. }
  79975. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  79976. var _this = this;
  79977. if (useOverlay === void 0) { useOverlay = false; }
  79978. var scene = this._scene;
  79979. var engine = this._scene.getEngine();
  79980. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79981. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  79982. return;
  79983. }
  79984. var mesh = subMesh.getRenderingMesh();
  79985. var material = subMesh.getMaterial();
  79986. if (!material || !scene.activeCamera) {
  79987. return;
  79988. }
  79989. engine.enableEffect(this._effect);
  79990. // Logarithmic depth
  79991. if (material.useLogarithmicDepth) {
  79992. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  79993. }
  79994. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  79995. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  79996. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79997. // Bones
  79998. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79999. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80000. }
  80001. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  80002. // Alpha test
  80003. if (material && material.needAlphaTesting()) {
  80004. var alphaTexture = material.getAlphaTestTexture();
  80005. if (alphaTexture) {
  80006. this._effect.setTexture("diffuseSampler", alphaTexture);
  80007. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80008. }
  80009. }
  80010. engine.setZOffset(-this.zOffset);
  80011. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  80012. engine.setZOffset(0);
  80013. };
  80014. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  80015. var defines = [];
  80016. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80017. var mesh = subMesh.getMesh();
  80018. var material = subMesh.getMaterial();
  80019. if (material) {
  80020. // Alpha test
  80021. if (material.needAlphaTesting()) {
  80022. defines.push("#define ALPHATEST");
  80023. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80024. attribs.push(BABYLON.VertexBuffer.UVKind);
  80025. defines.push("#define UV1");
  80026. }
  80027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80028. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80029. defines.push("#define UV2");
  80030. }
  80031. }
  80032. //Logarithmic depth
  80033. if (material.useLogarithmicDepth) {
  80034. defines.push("#define LOGARITHMICDEPTH");
  80035. }
  80036. }
  80037. // Bones
  80038. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80039. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80040. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80041. if (mesh.numBoneInfluencers > 4) {
  80042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80044. }
  80045. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80046. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80047. }
  80048. else {
  80049. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80050. }
  80051. // Instances
  80052. if (useInstances) {
  80053. defines.push("#define INSTANCES");
  80054. attribs.push("world0");
  80055. attribs.push("world1");
  80056. attribs.push("world2");
  80057. attribs.push("world3");
  80058. }
  80059. // Get correct effect
  80060. var join = defines.join("\n");
  80061. if (this._cachedDefines !== join) {
  80062. this._cachedDefines = join;
  80063. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  80064. }
  80065. return this._effect.isReady();
  80066. };
  80067. return OutlineRenderer;
  80068. }());
  80069. BABYLON.OutlineRenderer = OutlineRenderer;
  80070. })(BABYLON || (BABYLON = {}));
  80071. //# sourceMappingURL=babylon.outlineRenderer.js.map
  80072. var BABYLON;
  80073. (function (BABYLON) {
  80074. var FaceAdjacencies = /** @class */ (function () {
  80075. function FaceAdjacencies() {
  80076. this.edges = new Array();
  80077. this.edgesConnectedCount = 0;
  80078. }
  80079. return FaceAdjacencies;
  80080. }());
  80081. var EdgesRenderer = /** @class */ (function () {
  80082. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  80083. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  80084. if (epsilon === void 0) { epsilon = 0.95; }
  80085. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  80086. this.edgesWidthScalerForOrthographic = 1000.0;
  80087. this.edgesWidthScalerForPerspective = 50.0;
  80088. this._linesPositions = new Array();
  80089. this._linesNormals = new Array();
  80090. this._linesIndices = new Array();
  80091. this._buffers = {};
  80092. this._checkVerticesInsteadOfIndices = false;
  80093. this._source = source;
  80094. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  80095. this._epsilon = epsilon;
  80096. this._prepareRessources();
  80097. this._generateEdgesLines();
  80098. }
  80099. EdgesRenderer.prototype._prepareRessources = function () {
  80100. if (this._lineShader) {
  80101. return;
  80102. }
  80103. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  80104. attributes: ["position", "normal"],
  80105. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  80106. });
  80107. this._lineShader.disableDepthWrite = true;
  80108. this._lineShader.backFaceCulling = false;
  80109. };
  80110. EdgesRenderer.prototype._rebuild = function () {
  80111. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  80112. if (buffer) {
  80113. buffer._rebuild();
  80114. }
  80115. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  80116. if (buffer) {
  80117. buffer._rebuild();
  80118. }
  80119. var scene = this._source.getScene();
  80120. var engine = scene.getEngine();
  80121. this._ib = engine.createIndexBuffer(this._linesIndices);
  80122. };
  80123. EdgesRenderer.prototype.dispose = function () {
  80124. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  80125. if (buffer) {
  80126. buffer.dispose();
  80127. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  80128. }
  80129. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  80130. if (buffer) {
  80131. buffer.dispose();
  80132. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  80133. }
  80134. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  80135. this._lineShader.dispose();
  80136. };
  80137. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  80138. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  80139. return 0;
  80140. }
  80141. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  80142. return 1;
  80143. }
  80144. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  80145. return 2;
  80146. }
  80147. return -1;
  80148. };
  80149. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  80150. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  80151. return 0;
  80152. }
  80153. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  80154. return 1;
  80155. }
  80156. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  80157. return 2;
  80158. }
  80159. return -1;
  80160. };
  80161. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  80162. var needToCreateLine;
  80163. if (edge === undefined) {
  80164. needToCreateLine = true;
  80165. }
  80166. else {
  80167. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  80168. needToCreateLine = dotProduct < this._epsilon;
  80169. }
  80170. if (needToCreateLine) {
  80171. var offset = this._linesPositions.length / 3;
  80172. var normal = p0.subtract(p1);
  80173. normal.normalize();
  80174. // Positions
  80175. this._linesPositions.push(p0.x);
  80176. this._linesPositions.push(p0.y);
  80177. this._linesPositions.push(p0.z);
  80178. this._linesPositions.push(p0.x);
  80179. this._linesPositions.push(p0.y);
  80180. this._linesPositions.push(p0.z);
  80181. this._linesPositions.push(p1.x);
  80182. this._linesPositions.push(p1.y);
  80183. this._linesPositions.push(p1.z);
  80184. this._linesPositions.push(p1.x);
  80185. this._linesPositions.push(p1.y);
  80186. this._linesPositions.push(p1.z);
  80187. // Normals
  80188. this._linesNormals.push(p1.x);
  80189. this._linesNormals.push(p1.y);
  80190. this._linesNormals.push(p1.z);
  80191. this._linesNormals.push(-1);
  80192. this._linesNormals.push(p1.x);
  80193. this._linesNormals.push(p1.y);
  80194. this._linesNormals.push(p1.z);
  80195. this._linesNormals.push(1);
  80196. this._linesNormals.push(p0.x);
  80197. this._linesNormals.push(p0.y);
  80198. this._linesNormals.push(p0.z);
  80199. this._linesNormals.push(-1);
  80200. this._linesNormals.push(p0.x);
  80201. this._linesNormals.push(p0.y);
  80202. this._linesNormals.push(p0.z);
  80203. this._linesNormals.push(1);
  80204. // Indices
  80205. this._linesIndices.push(offset);
  80206. this._linesIndices.push(offset + 1);
  80207. this._linesIndices.push(offset + 2);
  80208. this._linesIndices.push(offset);
  80209. this._linesIndices.push(offset + 2);
  80210. this._linesIndices.push(offset + 3);
  80211. }
  80212. };
  80213. EdgesRenderer.prototype._generateEdgesLines = function () {
  80214. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80215. var indices = this._source.getIndices();
  80216. if (!indices || !positions) {
  80217. return;
  80218. }
  80219. // First let's find adjacencies
  80220. var adjacencies = new Array();
  80221. var faceNormals = new Array();
  80222. var index;
  80223. var faceAdjacencies;
  80224. // Prepare faces
  80225. for (index = 0; index < indices.length; index += 3) {
  80226. faceAdjacencies = new FaceAdjacencies();
  80227. var p0Index = indices[index];
  80228. var p1Index = indices[index + 1];
  80229. var p2Index = indices[index + 2];
  80230. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  80231. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  80232. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  80233. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  80234. faceNormal.normalize();
  80235. faceNormals.push(faceNormal);
  80236. adjacencies.push(faceAdjacencies);
  80237. }
  80238. // Scan
  80239. for (index = 0; index < adjacencies.length; index++) {
  80240. faceAdjacencies = adjacencies[index];
  80241. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  80242. var otherFaceAdjacencies = adjacencies[otherIndex];
  80243. if (faceAdjacencies.edgesConnectedCount === 3) {
  80244. break;
  80245. }
  80246. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  80247. continue;
  80248. }
  80249. var otherP0 = indices[otherIndex * 3];
  80250. var otherP1 = indices[otherIndex * 3 + 1];
  80251. var otherP2 = indices[otherIndex * 3 + 2];
  80252. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  80253. var otherEdgeIndex = 0;
  80254. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  80255. continue;
  80256. }
  80257. switch (edgeIndex) {
  80258. case 0:
  80259. if (this._checkVerticesInsteadOfIndices) {
  80260. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80261. }
  80262. else {
  80263. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  80264. }
  80265. break;
  80266. case 1:
  80267. if (this._checkVerticesInsteadOfIndices) {
  80268. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80269. }
  80270. else {
  80271. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  80272. }
  80273. break;
  80274. case 2:
  80275. if (this._checkVerticesInsteadOfIndices) {
  80276. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80277. }
  80278. else {
  80279. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  80280. }
  80281. break;
  80282. }
  80283. if (otherEdgeIndex === -1) {
  80284. continue;
  80285. }
  80286. faceAdjacencies.edges[edgeIndex] = otherIndex;
  80287. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  80288. faceAdjacencies.edgesConnectedCount++;
  80289. otherFaceAdjacencies.edgesConnectedCount++;
  80290. if (faceAdjacencies.edgesConnectedCount === 3) {
  80291. break;
  80292. }
  80293. }
  80294. }
  80295. }
  80296. // Create lines
  80297. for (index = 0; index < adjacencies.length; index++) {
  80298. // 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
  80299. var current = adjacencies[index];
  80300. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  80301. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  80302. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  80303. }
  80304. // Merge into a single mesh
  80305. var engine = this._source.getScene().getEngine();
  80306. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  80307. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  80308. this._ib = engine.createIndexBuffer(this._linesIndices);
  80309. this._indicesCount = this._linesIndices.length;
  80310. };
  80311. EdgesRenderer.prototype.render = function () {
  80312. var scene = this._source.getScene();
  80313. if (!this._lineShader.isReady() || !scene.activeCamera) {
  80314. return;
  80315. }
  80316. var engine = scene.getEngine();
  80317. this._lineShader._preBind();
  80318. // VBOs
  80319. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  80320. scene.resetCachedMaterial();
  80321. this._lineShader.setColor4("color", this._source.edgesColor);
  80322. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  80323. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  80324. }
  80325. else {
  80326. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  80327. }
  80328. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  80329. this._lineShader.bind(this._source.getWorldMatrix());
  80330. // Draw order
  80331. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  80332. this._lineShader.unbind();
  80333. engine.setDepthWrite(true);
  80334. };
  80335. return EdgesRenderer;
  80336. }());
  80337. BABYLON.EdgesRenderer = EdgesRenderer;
  80338. })(BABYLON || (BABYLON = {}));
  80339. //# sourceMappingURL=babylon.edgesRenderer.js.map
  80340. var BABYLON;
  80341. (function (BABYLON) {
  80342. /**
  80343. * Special Glow Blur post process only blurring the alpha channel
  80344. * It enforces keeping the most luminous color in the color channel.
  80345. */
  80346. var GlowBlurPostProcess = /** @class */ (function (_super) {
  80347. __extends(GlowBlurPostProcess, _super);
  80348. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  80349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80350. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  80351. _this.direction = direction;
  80352. _this.kernel = kernel;
  80353. _this.onApplyObservable.add(function (effect) {
  80354. effect.setFloat2("screenSize", _this.width, _this.height);
  80355. effect.setVector2("direction", _this.direction);
  80356. effect.setFloat("blurWidth", _this.kernel);
  80357. });
  80358. return _this;
  80359. }
  80360. return GlowBlurPostProcess;
  80361. }(BABYLON.PostProcess));
  80362. /**
  80363. * The highlight layer Helps adding a glow effect around a mesh.
  80364. *
  80365. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  80366. * glowy meshes to your scene.
  80367. *
  80368. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  80369. */
  80370. var HighlightLayer = /** @class */ (function () {
  80371. /**
  80372. * Instantiates a new highlight Layer and references it to the scene..
  80373. * @param name The name of the layer
  80374. * @param scene The scene to use the layer in
  80375. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  80376. */
  80377. function HighlightLayer(name, scene, options) {
  80378. this.name = name;
  80379. this._vertexBuffers = {};
  80380. this._mainTextureDesiredSize = { width: 0, height: 0 };
  80381. this._meshes = {};
  80382. this._maxSize = 0;
  80383. this._shouldRender = false;
  80384. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  80385. this._excludedMeshes = {};
  80386. /**
  80387. * Specifies whether or not the inner glow is ACTIVE in the layer.
  80388. */
  80389. this.innerGlow = true;
  80390. /**
  80391. * Specifies whether or not the outer glow is ACTIVE in the layer.
  80392. */
  80393. this.outerGlow = true;
  80394. /**
  80395. * Specifies wether the highlight layer is enabled or not.
  80396. */
  80397. this.isEnabled = true;
  80398. /**
  80399. * An event triggered when the highlight layer has been disposed.
  80400. * @type {BABYLON.Observable}
  80401. */
  80402. this.onDisposeObservable = new BABYLON.Observable();
  80403. /**
  80404. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  80405. * @type {BABYLON.Observable}
  80406. */
  80407. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  80408. /**
  80409. * An event triggered when the highlight layer is being blurred.
  80410. * @type {BABYLON.Observable}
  80411. */
  80412. this.onBeforeBlurObservable = new BABYLON.Observable();
  80413. /**
  80414. * An event triggered when the highlight layer has been blurred.
  80415. * @type {BABYLON.Observable}
  80416. */
  80417. this.onAfterBlurObservable = new BABYLON.Observable();
  80418. /**
  80419. * An event triggered when the glowing blurred texture is being merged in the scene.
  80420. * @type {BABYLON.Observable}
  80421. */
  80422. this.onBeforeComposeObservable = new BABYLON.Observable();
  80423. /**
  80424. * An event triggered when the glowing blurred texture has been merged in the scene.
  80425. * @type {BABYLON.Observable}
  80426. */
  80427. this.onAfterComposeObservable = new BABYLON.Observable();
  80428. /**
  80429. * An event triggered when the highlight layer changes its size.
  80430. * @type {BABYLON.Observable}
  80431. */
  80432. this.onSizeChangedObservable = new BABYLON.Observable();
  80433. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80434. var engine = scene.getEngine();
  80435. this._engine = engine;
  80436. this._maxSize = this._engine.getCaps().maxTextureSize;
  80437. this._scene.highlightLayers.push(this);
  80438. // Warn on stencil.
  80439. if (!this._engine.isStencilEnable) {
  80440. 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 }");
  80441. }
  80442. // Adapt options
  80443. this._options = options || {
  80444. mainTextureRatio: 0.5,
  80445. blurTextureSizeRatio: 0.5,
  80446. blurHorizontalSize: 1.0,
  80447. blurVerticalSize: 1.0,
  80448. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  80449. camera: null
  80450. };
  80451. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  80452. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  80453. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  80454. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  80455. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80456. // VBO
  80457. var vertices = [];
  80458. vertices.push(1, 1);
  80459. vertices.push(-1, 1);
  80460. vertices.push(-1, -1);
  80461. vertices.push(1, -1);
  80462. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80464. this._createIndexBuffer();
  80465. // Effect
  80466. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80467. // Render target
  80468. this.setMainTextureSize();
  80469. // Create Textures and post processes
  80470. this.createTextureAndPostProcesses();
  80471. }
  80472. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80473. /**
  80474. * Gets the horizontal size of the blur.
  80475. */
  80476. get: function () {
  80477. return this._horizontalBlurPostprocess.kernel;
  80478. },
  80479. /**
  80480. * Specifies the horizontal size of the blur.
  80481. */
  80482. set: function (value) {
  80483. this._horizontalBlurPostprocess.kernel = value;
  80484. },
  80485. enumerable: true,
  80486. configurable: true
  80487. });
  80488. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80489. /**
  80490. * Gets the vertical size of the blur.
  80491. */
  80492. get: function () {
  80493. return this._verticalBlurPostprocess.kernel;
  80494. },
  80495. /**
  80496. * Specifies the vertical size of the blur.
  80497. */
  80498. set: function (value) {
  80499. this._verticalBlurPostprocess.kernel = value;
  80500. },
  80501. enumerable: true,
  80502. configurable: true
  80503. });
  80504. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80505. /**
  80506. * Gets the camera attached to the layer.
  80507. */
  80508. get: function () {
  80509. return this._options.camera;
  80510. },
  80511. enumerable: true,
  80512. configurable: true
  80513. });
  80514. HighlightLayer.prototype._createIndexBuffer = function () {
  80515. var engine = this._scene.getEngine();
  80516. // Indices
  80517. var indices = [];
  80518. indices.push(0);
  80519. indices.push(1);
  80520. indices.push(2);
  80521. indices.push(0);
  80522. indices.push(2);
  80523. indices.push(3);
  80524. this._indexBuffer = engine.createIndexBuffer(indices);
  80525. };
  80526. HighlightLayer.prototype._rebuild = function () {
  80527. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80528. if (vb) {
  80529. vb._rebuild();
  80530. }
  80531. this._createIndexBuffer();
  80532. };
  80533. /**
  80534. * Creates the render target textures and post processes used in the highlight layer.
  80535. */
  80536. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80537. var _this = this;
  80538. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80539. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80540. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80541. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80542. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80543. width: this._mainTextureDesiredSize.width,
  80544. height: this._mainTextureDesiredSize.height
  80545. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80546. this._mainTexture.activeCamera = this._options.camera;
  80547. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80548. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80549. this._mainTexture.anisotropicFilteringLevel = 1;
  80550. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80551. this._mainTexture.renderParticles = false;
  80552. this._mainTexture.renderList = null;
  80553. this._mainTexture.ignoreCameraViewport = true;
  80554. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80555. width: blurTextureWidth,
  80556. height: blurTextureHeight
  80557. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80558. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80559. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80560. this._blurTexture.anisotropicFilteringLevel = 16;
  80561. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80562. this._blurTexture.renderParticles = false;
  80563. this._blurTexture.ignoreCameraViewport = true;
  80564. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80565. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80566. effect.setTexture("textureSampler", _this._mainTexture);
  80567. });
  80568. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80569. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80570. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80571. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80572. });
  80573. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80574. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80575. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80576. });
  80577. }
  80578. else {
  80579. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80580. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80581. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80582. });
  80583. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80584. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80585. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80586. });
  80587. }
  80588. this._mainTexture.onAfterUnbindObservable.add(function () {
  80589. _this.onBeforeBlurObservable.notifyObservers(_this);
  80590. var internalTexture = _this._blurTexture.getInternalTexture();
  80591. if (internalTexture) {
  80592. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80593. }
  80594. _this.onAfterBlurObservable.notifyObservers(_this);
  80595. });
  80596. // Custom render function
  80597. var renderSubMesh = function (subMesh) {
  80598. if (!_this._meshes) {
  80599. return;
  80600. }
  80601. var material = subMesh.getMaterial();
  80602. var mesh = subMesh.getRenderingMesh();
  80603. var scene = _this._scene;
  80604. var engine = scene.getEngine();
  80605. if (!material) {
  80606. return;
  80607. }
  80608. // Do not block in blend mode.
  80609. if (material.needAlphaBlendingForMesh(mesh)) {
  80610. return;
  80611. }
  80612. // Culling
  80613. engine.setState(material.backFaceCulling);
  80614. // Managing instances
  80615. var batch = mesh._getInstancesRenderList(subMesh._id);
  80616. if (batch.mustReturn) {
  80617. return;
  80618. }
  80619. // Excluded Mesh
  80620. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80621. return;
  80622. }
  80623. ;
  80624. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80625. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80626. var emissiveTexture = null;
  80627. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80628. emissiveTexture = material.emissiveTexture;
  80629. }
  80630. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80631. engine.enableEffect(_this._glowMapGenerationEffect);
  80632. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80633. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80634. if (highlightLayerMesh) {
  80635. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80636. }
  80637. else {
  80638. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80639. }
  80640. // Alpha test
  80641. if (material && material.needAlphaTesting()) {
  80642. var alphaTexture = material.getAlphaTestTexture();
  80643. if (alphaTexture) {
  80644. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80645. var textureMatrix = alphaTexture.getTextureMatrix();
  80646. if (textureMatrix) {
  80647. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80648. }
  80649. }
  80650. }
  80651. // Glow emissive only
  80652. if (emissiveTexture) {
  80653. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80654. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80655. }
  80656. // Bones
  80657. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80658. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80659. }
  80660. // Draw
  80661. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80662. }
  80663. else {
  80664. // Need to reset refresh rate of the shadowMap
  80665. _this._mainTexture.resetRefreshCounter();
  80666. }
  80667. };
  80668. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80669. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80670. var index;
  80671. var engine = _this._scene.getEngine();
  80672. if (depthOnlySubMeshes.length) {
  80673. engine.setColorWrite(false);
  80674. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80675. renderSubMesh(depthOnlySubMeshes.data[index]);
  80676. }
  80677. engine.setColorWrite(true);
  80678. }
  80679. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80680. renderSubMesh(opaqueSubMeshes.data[index]);
  80681. }
  80682. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80683. renderSubMesh(alphaTestSubMeshes.data[index]);
  80684. }
  80685. for (index = 0; index < transparentSubMeshes.length; index++) {
  80686. renderSubMesh(transparentSubMeshes.data[index]);
  80687. }
  80688. };
  80689. this._mainTexture.onClearObservable.add(function (engine) {
  80690. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80691. });
  80692. };
  80693. /**
  80694. * Checks for the readiness of the element composing the layer.
  80695. * @param subMesh the mesh to check for
  80696. * @param useInstances specify wether or not to use instances to render the mesh
  80697. * @param emissiveTexture the associated emissive texture used to generate the glow
  80698. * @return true if ready otherwise, false
  80699. */
  80700. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80701. var material = subMesh.getMaterial();
  80702. var mesh = subMesh.getRenderingMesh();
  80703. if (!material || !mesh || !this._meshes) {
  80704. return false;
  80705. }
  80706. var emissiveTexture = null;
  80707. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80708. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80709. emissiveTexture = material.emissiveTexture;
  80710. }
  80711. return this._isReady(subMesh, useInstances, emissiveTexture);
  80712. };
  80713. /**
  80714. * Checks for the readiness of the element composing the layer.
  80715. * @param subMesh the mesh to check for
  80716. * @param useInstances specify wether or not to use instances to render the mesh
  80717. * @param emissiveTexture the associated emissive texture used to generate the glow
  80718. * @return true if ready otherwise, false
  80719. */
  80720. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80721. var material = subMesh.getMaterial();
  80722. if (!material) {
  80723. return false;
  80724. }
  80725. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80726. return false;
  80727. }
  80728. var defines = [];
  80729. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80730. var mesh = subMesh.getMesh();
  80731. var uv1 = false;
  80732. var uv2 = false;
  80733. // Alpha test
  80734. if (material && material.needAlphaTesting()) {
  80735. var alphaTexture = material.getAlphaTestTexture();
  80736. if (alphaTexture) {
  80737. defines.push("#define ALPHATEST");
  80738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80739. alphaTexture.coordinatesIndex === 1) {
  80740. defines.push("#define DIFFUSEUV2");
  80741. uv2 = true;
  80742. }
  80743. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80744. defines.push("#define DIFFUSEUV1");
  80745. uv1 = true;
  80746. }
  80747. }
  80748. }
  80749. // Emissive
  80750. if (emissiveTexture) {
  80751. defines.push("#define EMISSIVE");
  80752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80753. emissiveTexture.coordinatesIndex === 1) {
  80754. defines.push("#define EMISSIVEUV2");
  80755. uv2 = true;
  80756. }
  80757. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80758. defines.push("#define EMISSIVEUV1");
  80759. uv1 = true;
  80760. }
  80761. }
  80762. if (uv1) {
  80763. attribs.push(BABYLON.VertexBuffer.UVKind);
  80764. defines.push("#define UV1");
  80765. }
  80766. if (uv2) {
  80767. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80768. defines.push("#define UV2");
  80769. }
  80770. // Bones
  80771. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80774. if (mesh.numBoneInfluencers > 4) {
  80775. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80776. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80777. }
  80778. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80779. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80780. }
  80781. else {
  80782. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80783. }
  80784. // Instances
  80785. if (useInstances) {
  80786. defines.push("#define INSTANCES");
  80787. attribs.push("world0");
  80788. attribs.push("world1");
  80789. attribs.push("world2");
  80790. attribs.push("world3");
  80791. }
  80792. // Get correct effect
  80793. var join = defines.join("\n");
  80794. if (this._cachedDefines !== join) {
  80795. this._cachedDefines = join;
  80796. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  80797. }
  80798. return this._glowMapGenerationEffect.isReady();
  80799. };
  80800. /**
  80801. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  80802. */
  80803. HighlightLayer.prototype.render = function () {
  80804. var currentEffect = this._glowMapMergeEffect;
  80805. // Check
  80806. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  80807. return;
  80808. var engine = this._scene.getEngine();
  80809. this.onBeforeComposeObservable.notifyObservers(this);
  80810. // Render
  80811. engine.enableEffect(currentEffect);
  80812. engine.setState(false);
  80813. // Cache
  80814. var previousStencilBuffer = engine.getStencilBuffer();
  80815. var previousStencilFunction = engine.getStencilFunction();
  80816. var previousStencilMask = engine.getStencilMask();
  80817. var previousStencilOperationPass = engine.getStencilOperationPass();
  80818. var previousStencilOperationFail = engine.getStencilOperationFail();
  80819. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  80820. var previousAlphaMode = engine.getAlphaMode();
  80821. // Texture
  80822. currentEffect.setTexture("textureSampler", this._blurTexture);
  80823. // VBOs
  80824. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80825. // Stencil operations
  80826. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  80827. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  80828. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  80829. // Draw order
  80830. engine.setAlphaMode(this._options.alphaBlendingMode);
  80831. engine.setStencilMask(0x00);
  80832. engine.setStencilBuffer(true);
  80833. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  80834. if (this.outerGlow) {
  80835. currentEffect.setFloat("offset", 0);
  80836. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  80837. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80838. }
  80839. if (this.innerGlow) {
  80840. currentEffect.setFloat("offset", 1);
  80841. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  80842. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80843. }
  80844. // Restore Cache
  80845. engine.setStencilFunction(previousStencilFunction);
  80846. engine.setStencilMask(previousStencilMask);
  80847. engine.setAlphaMode(previousAlphaMode);
  80848. engine.setStencilBuffer(previousStencilBuffer);
  80849. engine.setStencilOperationPass(previousStencilOperationPass);
  80850. engine.setStencilOperationFail(previousStencilOperationFail);
  80851. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  80852. engine._stencilState.reset();
  80853. this.onAfterComposeObservable.notifyObservers(this);
  80854. // Handle size changes.
  80855. var size = this._mainTexture.getSize();
  80856. this.setMainTextureSize();
  80857. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  80858. // Recreate RTT and post processes on size change.
  80859. this.onSizeChangedObservable.notifyObservers(this);
  80860. this.disposeTextureAndPostProcesses();
  80861. this.createTextureAndPostProcesses();
  80862. }
  80863. };
  80864. /**
  80865. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  80866. * @param mesh The mesh to exclude from the highlight layer
  80867. */
  80868. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  80869. if (!this._excludedMeshes) {
  80870. return;
  80871. }
  80872. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80873. if (!meshExcluded) {
  80874. this._excludedMeshes[mesh.uniqueId] = {
  80875. mesh: mesh,
  80876. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  80877. mesh.getEngine().setStencilBuffer(false);
  80878. }),
  80879. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  80880. mesh.getEngine().setStencilBuffer(true);
  80881. }),
  80882. };
  80883. }
  80884. };
  80885. /**
  80886. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  80887. * @param mesh The mesh to highlight
  80888. */
  80889. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  80890. if (!this._excludedMeshes) {
  80891. return;
  80892. }
  80893. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80894. if (meshExcluded) {
  80895. if (meshExcluded.beforeRender) {
  80896. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  80897. }
  80898. if (meshExcluded.afterRender) {
  80899. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  80900. }
  80901. }
  80902. this._excludedMeshes[mesh.uniqueId] = null;
  80903. };
  80904. /**
  80905. * Determine if a given mesh will be highlighted by the current HighlightLayer
  80906. * @param mesh mesh to test
  80907. * @returns true if the mesh will be highlighted by the current HighlightLayer
  80908. */
  80909. HighlightLayer.prototype.hasMesh = function (mesh) {
  80910. if (!this._meshes) {
  80911. return false;
  80912. }
  80913. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  80914. };
  80915. /**
  80916. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  80917. * @param mesh The mesh to highlight
  80918. * @param color The color of the highlight
  80919. * @param glowEmissiveOnly Extract the glow from the emissive texture
  80920. */
  80921. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  80922. var _this = this;
  80923. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  80924. if (!this._meshes) {
  80925. return;
  80926. }
  80927. var meshHighlight = this._meshes[mesh.uniqueId];
  80928. if (meshHighlight) {
  80929. meshHighlight.color = color;
  80930. }
  80931. else {
  80932. this._meshes[mesh.uniqueId] = {
  80933. mesh: mesh,
  80934. color: color,
  80935. // Lambda required for capture due to Observable this context
  80936. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  80937. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80938. _this.defaultStencilReference(mesh);
  80939. }
  80940. else {
  80941. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  80942. }
  80943. }),
  80944. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  80945. glowEmissiveOnly: glowEmissiveOnly
  80946. };
  80947. }
  80948. this._shouldRender = true;
  80949. };
  80950. /**
  80951. * Remove a mesh from the highlight layer in order to make it stop glowing.
  80952. * @param mesh The mesh to highlight
  80953. */
  80954. HighlightLayer.prototype.removeMesh = function (mesh) {
  80955. if (!this._meshes) {
  80956. return;
  80957. }
  80958. var meshHighlight = this._meshes[mesh.uniqueId];
  80959. if (meshHighlight) {
  80960. if (meshHighlight.observerHighlight) {
  80961. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80962. }
  80963. if (meshHighlight.observerDefault) {
  80964. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80965. }
  80966. delete this._meshes[mesh.uniqueId];
  80967. }
  80968. this._shouldRender = false;
  80969. for (var meshHighlightToCheck in this._meshes) {
  80970. if (this._meshes[meshHighlightToCheck]) {
  80971. this._shouldRender = true;
  80972. break;
  80973. }
  80974. }
  80975. };
  80976. /**
  80977. * Returns true if the layer contains information to display, otherwise false.
  80978. */
  80979. HighlightLayer.prototype.shouldRender = function () {
  80980. return this.isEnabled && this._shouldRender;
  80981. };
  80982. /**
  80983. * Sets the main texture desired size which is the closest power of two
  80984. * of the engine canvas size.
  80985. */
  80986. HighlightLayer.prototype.setMainTextureSize = function () {
  80987. if (this._options.mainTextureFixedSize) {
  80988. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  80989. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  80990. }
  80991. else {
  80992. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  80993. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  80994. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  80995. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  80996. }
  80997. };
  80998. /**
  80999. * Force the stencil to the normal expected value for none glowing parts
  81000. */
  81001. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  81002. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  81003. };
  81004. /**
  81005. * Dispose only the render target textures and post process.
  81006. */
  81007. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  81008. this._blurTexture.dispose();
  81009. this._mainTexture.dispose();
  81010. this._downSamplePostprocess.dispose();
  81011. this._horizontalBlurPostprocess.dispose();
  81012. this._verticalBlurPostprocess.dispose();
  81013. };
  81014. /**
  81015. * Dispose the highlight layer and free resources.
  81016. */
  81017. HighlightLayer.prototype.dispose = function () {
  81018. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81019. if (vertexBuffer) {
  81020. vertexBuffer.dispose();
  81021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81022. }
  81023. if (this._indexBuffer) {
  81024. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81025. this._indexBuffer = null;
  81026. }
  81027. // Clean textures and post processes
  81028. this.disposeTextureAndPostProcesses();
  81029. if (this._meshes) {
  81030. // Clean mesh references
  81031. for (var id in this._meshes) {
  81032. var meshHighlight = this._meshes[id];
  81033. if (meshHighlight && meshHighlight.mesh) {
  81034. if (meshHighlight.observerHighlight) {
  81035. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  81036. }
  81037. if (meshHighlight.observerDefault) {
  81038. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  81039. }
  81040. }
  81041. }
  81042. this._meshes = null;
  81043. }
  81044. if (this._excludedMeshes) {
  81045. for (var id in this._excludedMeshes) {
  81046. var meshHighlight = this._excludedMeshes[id];
  81047. if (meshHighlight) {
  81048. if (meshHighlight.beforeRender) {
  81049. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  81050. }
  81051. if (meshHighlight.afterRender) {
  81052. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  81053. }
  81054. }
  81055. }
  81056. this._excludedMeshes = null;
  81057. }
  81058. // Remove from scene
  81059. var index = this._scene.highlightLayers.indexOf(this, 0);
  81060. if (index > -1) {
  81061. this._scene.highlightLayers.splice(index, 1);
  81062. }
  81063. // Callback
  81064. this.onDisposeObservable.notifyObservers(this);
  81065. this.onDisposeObservable.clear();
  81066. this.onBeforeRenderMainTextureObservable.clear();
  81067. this.onBeforeBlurObservable.clear();
  81068. this.onBeforeComposeObservable.clear();
  81069. this.onAfterComposeObservable.clear();
  81070. this.onSizeChangedObservable.clear();
  81071. };
  81072. /**
  81073. * The neutral color used during the preparation of the glow effect.
  81074. * This is black by default as the blend operation is a blend operation.
  81075. */
  81076. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  81077. /**
  81078. * Stencil value used for glowing meshes.
  81079. */
  81080. HighlightLayer.glowingMeshStencilReference = 0x02;
  81081. /**
  81082. * Stencil value used for the other meshes in the scene.
  81083. */
  81084. HighlightLayer.normalMeshStencilReference = 0x01;
  81085. return HighlightLayer;
  81086. }());
  81087. BABYLON.HighlightLayer = HighlightLayer;
  81088. })(BABYLON || (BABYLON = {}));
  81089. //# sourceMappingURL=babylon.highlightlayer.js.map
  81090. var BABYLON;
  81091. (function (BABYLON) {
  81092. /**
  81093. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  81094. */
  81095. var AssetTaskState;
  81096. (function (AssetTaskState) {
  81097. /**
  81098. * Initialization
  81099. */
  81100. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  81101. /**
  81102. * Running
  81103. */
  81104. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  81105. /**
  81106. * Done
  81107. */
  81108. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  81109. /**
  81110. * Error
  81111. */
  81112. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  81113. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  81114. /**
  81115. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  81116. */
  81117. var AbstractAssetTask = /** @class */ (function () {
  81118. /**
  81119. * Creates a new {BABYLON.AssetsManager}
  81120. * @param name defines the name of the task
  81121. */
  81122. function AbstractAssetTask(
  81123. /**
  81124. * Task name
  81125. */ name) {
  81126. this.name = name;
  81127. this._isCompleted = false;
  81128. this._taskState = AssetTaskState.INIT;
  81129. }
  81130. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  81131. /**
  81132. * Get if the task is completed
  81133. */
  81134. get: function () {
  81135. return this._isCompleted;
  81136. },
  81137. enumerable: true,
  81138. configurable: true
  81139. });
  81140. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  81141. /**
  81142. * Gets the current state of the task
  81143. */
  81144. get: function () {
  81145. return this._taskState;
  81146. },
  81147. enumerable: true,
  81148. configurable: true
  81149. });
  81150. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  81151. /**
  81152. * Gets the current error object (if task is in error)
  81153. */
  81154. get: function () {
  81155. return this._errorObject;
  81156. },
  81157. enumerable: true,
  81158. configurable: true
  81159. });
  81160. /**
  81161. * Internal only
  81162. * @ignore
  81163. */
  81164. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  81165. if (this._errorObject) {
  81166. return;
  81167. }
  81168. this._errorObject = {
  81169. message: message,
  81170. exception: exception
  81171. };
  81172. };
  81173. /**
  81174. * Execute the current task
  81175. * @param scene defines the scene where you want your assets to be loaded
  81176. * @param onSuccess is a callback called when the task is successfully executed
  81177. * @param onError is a callback called if an error occurs
  81178. */
  81179. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81180. var _this = this;
  81181. this._taskState = AssetTaskState.RUNNING;
  81182. this.runTask(scene, function () {
  81183. _this.onDoneCallback(onSuccess, onError);
  81184. }, function (msg, exception) {
  81185. _this.onErrorCallback(onError, msg, exception);
  81186. });
  81187. };
  81188. /**
  81189. * Execute the current task
  81190. * @param scene defines the scene where you want your assets to be loaded
  81191. * @param onSuccess is a callback called when the task is successfully executed
  81192. * @param onError is a callback called if an error occurs
  81193. */
  81194. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81195. throw new Error("runTask is not implemented");
  81196. };
  81197. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  81198. this._taskState = AssetTaskState.ERROR;
  81199. this._errorObject = {
  81200. message: message,
  81201. exception: exception
  81202. };
  81203. if (this.onError) {
  81204. this.onError(this, message, exception);
  81205. }
  81206. onError();
  81207. };
  81208. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  81209. try {
  81210. this._taskState = AssetTaskState.DONE;
  81211. this._isCompleted = true;
  81212. if (this.onSuccess) {
  81213. this.onSuccess(this);
  81214. }
  81215. onSuccess();
  81216. }
  81217. catch (e) {
  81218. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  81219. }
  81220. };
  81221. return AbstractAssetTask;
  81222. }());
  81223. BABYLON.AbstractAssetTask = AbstractAssetTask;
  81224. /**
  81225. * Class used to share progress information about assets loading
  81226. */
  81227. var AssetsProgressEvent = /** @class */ (function () {
  81228. /**
  81229. * Creates a {BABYLON.AssetsProgressEvent}
  81230. * @param remainingCount defines the number of remaining tasks to process
  81231. * @param totalCount defines the total number of tasks
  81232. * @param task defines the task that was just processed
  81233. */
  81234. function AssetsProgressEvent(remainingCount, totalCount, task) {
  81235. this.remainingCount = remainingCount;
  81236. this.totalCount = totalCount;
  81237. this.task = task;
  81238. }
  81239. return AssetsProgressEvent;
  81240. }());
  81241. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  81242. /**
  81243. * Define a task used by {BABYLON.AssetsManager} to load meshes
  81244. */
  81245. var MeshAssetTask = /** @class */ (function (_super) {
  81246. __extends(MeshAssetTask, _super);
  81247. /**
  81248. * Creates a new {BABYLON.MeshAssetTask}
  81249. * @param name defines the name of the task
  81250. * @param meshesNames defines the list of mesh's names you want to load
  81251. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  81252. * @param sceneFilename defines the filename of the scene to load from
  81253. */
  81254. function MeshAssetTask(
  81255. /**
  81256. * Defines the name of the task
  81257. */
  81258. name,
  81259. /**
  81260. * Defines the list of mesh's names you want to load
  81261. */
  81262. meshesNames,
  81263. /**
  81264. * Defines the root url to use as a base to load your meshes and associated resources
  81265. */
  81266. rootUrl,
  81267. /**
  81268. * Defines the filename of the scene to load from
  81269. */
  81270. sceneFilename) {
  81271. var _this = _super.call(this, name) || this;
  81272. _this.name = name;
  81273. _this.meshesNames = meshesNames;
  81274. _this.rootUrl = rootUrl;
  81275. _this.sceneFilename = sceneFilename;
  81276. return _this;
  81277. }
  81278. /**
  81279. * Execute the current task
  81280. * @param scene defines the scene where you want your assets to be loaded
  81281. * @param onSuccess is a callback called when the task is successfully executed
  81282. * @param onError is a callback called if an error occurs
  81283. */
  81284. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81285. var _this = this;
  81286. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  81287. _this.loadedMeshes = meshes;
  81288. _this.loadedParticleSystems = particleSystems;
  81289. _this.loadedSkeletons = skeletons;
  81290. onSuccess();
  81291. }, null, function (scene, message, exception) {
  81292. onError(message, exception);
  81293. });
  81294. };
  81295. return MeshAssetTask;
  81296. }(AbstractAssetTask));
  81297. BABYLON.MeshAssetTask = MeshAssetTask;
  81298. /**
  81299. * Define a task used by {BABYLON.AssetsManager} to load text content
  81300. */
  81301. var TextFileAssetTask = /** @class */ (function (_super) {
  81302. __extends(TextFileAssetTask, _super);
  81303. /**
  81304. * Creates a new TextFileAssetTask object
  81305. * @param name defines the name of the task
  81306. * @param url defines the location of the file to load
  81307. */
  81308. function TextFileAssetTask(
  81309. /**
  81310. * Defines the name of the task
  81311. */
  81312. name,
  81313. /**
  81314. * Defines the location of the file to load
  81315. */
  81316. url) {
  81317. var _this = _super.call(this, name) || this;
  81318. _this.name = name;
  81319. _this.url = url;
  81320. return _this;
  81321. }
  81322. /**
  81323. * Execute the current task
  81324. * @param scene defines the scene where you want your assets to be loaded
  81325. * @param onSuccess is a callback called when the task is successfully executed
  81326. * @param onError is a callback called if an error occurs
  81327. */
  81328. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81329. var _this = this;
  81330. scene._loadFile(this.url, function (data) {
  81331. _this.text = data;
  81332. onSuccess();
  81333. }, undefined, false, true, function (request, exception) {
  81334. if (request) {
  81335. onError(request.status + " " + request.statusText, exception);
  81336. }
  81337. });
  81338. };
  81339. return TextFileAssetTask;
  81340. }(AbstractAssetTask));
  81341. BABYLON.TextFileAssetTask = TextFileAssetTask;
  81342. /**
  81343. * Define a task used by {BABYLON.AssetsManager} to load binary data
  81344. */
  81345. var BinaryFileAssetTask = /** @class */ (function (_super) {
  81346. __extends(BinaryFileAssetTask, _super);
  81347. /**
  81348. * Creates a new BinaryFileAssetTask object
  81349. * @param name defines the name of the new task
  81350. * @param url defines the location of the file to load
  81351. */
  81352. function BinaryFileAssetTask(
  81353. /**
  81354. * Defines the name of the task
  81355. */
  81356. name,
  81357. /**
  81358. * Defines the location of the file to load
  81359. */
  81360. url) {
  81361. var _this = _super.call(this, name) || this;
  81362. _this.name = name;
  81363. _this.url = url;
  81364. return _this;
  81365. }
  81366. /**
  81367. * Execute the current task
  81368. * @param scene defines the scene where you want your assets to be loaded
  81369. * @param onSuccess is a callback called when the task is successfully executed
  81370. * @param onError is a callback called if an error occurs
  81371. */
  81372. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81373. var _this = this;
  81374. scene._loadFile(this.url, function (data) {
  81375. _this.data = data;
  81376. onSuccess();
  81377. }, undefined, true, true, function (request, exception) {
  81378. if (request) {
  81379. onError(request.status + " " + request.statusText, exception);
  81380. }
  81381. });
  81382. };
  81383. return BinaryFileAssetTask;
  81384. }(AbstractAssetTask));
  81385. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  81386. /**
  81387. * Define a task used by {BABYLON.AssetsManager} to load images
  81388. */
  81389. var ImageAssetTask = /** @class */ (function (_super) {
  81390. __extends(ImageAssetTask, _super);
  81391. /**
  81392. * Creates a new ImageAssetTask
  81393. * @param name defines the name of the task
  81394. * @param url defines the location of the image to load
  81395. */
  81396. function ImageAssetTask(
  81397. /**
  81398. * Defines the name of the task
  81399. */
  81400. name,
  81401. /**
  81402. * Defines the location of the image to load
  81403. */
  81404. url) {
  81405. var _this = _super.call(this, name) || this;
  81406. _this.name = name;
  81407. _this.url = url;
  81408. return _this;
  81409. }
  81410. /**
  81411. * Execute the current task
  81412. * @param scene defines the scene where you want your assets to be loaded
  81413. * @param onSuccess is a callback called when the task is successfully executed
  81414. * @param onError is a callback called if an error occurs
  81415. */
  81416. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81417. var _this = this;
  81418. var img = new Image();
  81419. BABYLON.Tools.SetCorsBehavior(this.url, img);
  81420. img.onload = function () {
  81421. _this.image = img;
  81422. onSuccess();
  81423. };
  81424. img.onerror = function (err) {
  81425. onError("Error loading image", err);
  81426. };
  81427. img.src = this.url;
  81428. };
  81429. return ImageAssetTask;
  81430. }(AbstractAssetTask));
  81431. BABYLON.ImageAssetTask = ImageAssetTask;
  81432. /**
  81433. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  81434. */
  81435. var TextureAssetTask = /** @class */ (function (_super) {
  81436. __extends(TextureAssetTask, _super);
  81437. /**
  81438. * Creates a new TextureAssetTask object
  81439. * @param name defines the name of the task
  81440. * @param url defines the location of the file to load
  81441. * @param noMipmap defines if mipmap should not be generated (default is false)
  81442. * @param invertY defines if texture must be inverted on Y axis (default is false)
  81443. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81444. */
  81445. function TextureAssetTask(
  81446. /**
  81447. * Defines the name of the task
  81448. */
  81449. name,
  81450. /**
  81451. * Defines the location of the file to load
  81452. */
  81453. url,
  81454. /**
  81455. * Defines if mipmap should not be generated (default is false)
  81456. */
  81457. noMipmap,
  81458. /**
  81459. * Defines if texture must be inverted on Y axis (default is false)
  81460. */
  81461. invertY,
  81462. /**
  81463. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81464. */
  81465. samplingMode) {
  81466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81467. var _this = _super.call(this, name) || this;
  81468. _this.name = name;
  81469. _this.url = url;
  81470. _this.noMipmap = noMipmap;
  81471. _this.invertY = invertY;
  81472. _this.samplingMode = samplingMode;
  81473. return _this;
  81474. }
  81475. /**
  81476. * Execute the current task
  81477. * @param scene defines the scene where you want your assets to be loaded
  81478. * @param onSuccess is a callback called when the task is successfully executed
  81479. * @param onError is a callback called if an error occurs
  81480. */
  81481. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81482. var onload = function () {
  81483. onSuccess();
  81484. };
  81485. var onerror = function (message, exception) {
  81486. onError(message, exception);
  81487. };
  81488. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81489. };
  81490. return TextureAssetTask;
  81491. }(AbstractAssetTask));
  81492. BABYLON.TextureAssetTask = TextureAssetTask;
  81493. /**
  81494. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81495. */
  81496. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81497. __extends(CubeTextureAssetTask, _super);
  81498. /**
  81499. * Creates a new CubeTextureAssetTask
  81500. * @param name defines the name of the task
  81501. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81502. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81503. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81504. * @param files defines the explicit list of files (undefined by default)
  81505. */
  81506. function CubeTextureAssetTask(
  81507. /**
  81508. * Defines the name of the task
  81509. */
  81510. name,
  81511. /**
  81512. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81513. */
  81514. url,
  81515. /**
  81516. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81517. */
  81518. extensions,
  81519. /**
  81520. * Defines if mipmaps should not be generated (default is false)
  81521. */
  81522. noMipmap,
  81523. /**
  81524. * Defines the explicit list of files (undefined by default)
  81525. */
  81526. files) {
  81527. var _this = _super.call(this, name) || this;
  81528. _this.name = name;
  81529. _this.url = url;
  81530. _this.extensions = extensions;
  81531. _this.noMipmap = noMipmap;
  81532. _this.files = files;
  81533. return _this;
  81534. }
  81535. /**
  81536. * Execute the current task
  81537. * @param scene defines the scene where you want your assets to be loaded
  81538. * @param onSuccess is a callback called when the task is successfully executed
  81539. * @param onError is a callback called if an error occurs
  81540. */
  81541. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81542. var onload = function () {
  81543. onSuccess();
  81544. };
  81545. var onerror = function (message, exception) {
  81546. onError(message, exception);
  81547. };
  81548. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81549. };
  81550. return CubeTextureAssetTask;
  81551. }(AbstractAssetTask));
  81552. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81553. /**
  81554. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81555. */
  81556. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81557. __extends(HDRCubeTextureAssetTask, _super);
  81558. /**
  81559. * Creates a new HDRCubeTextureAssetTask object
  81560. * @param name defines the name of the task
  81561. * @param url defines the location of the file to load
  81562. * @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.
  81563. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81564. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81565. * @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)
  81566. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81567. */
  81568. function HDRCubeTextureAssetTask(
  81569. /**
  81570. * Defines the name of the task
  81571. */
  81572. name,
  81573. /**
  81574. * Defines the location of the file to load
  81575. */
  81576. url,
  81577. /**
  81578. * 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.
  81579. */
  81580. size,
  81581. /**
  81582. * Defines if mipmaps should not be generated (default is false)
  81583. */
  81584. noMipmap,
  81585. /**
  81586. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81587. */
  81588. generateHarmonics,
  81589. /**
  81590. * 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)
  81591. */
  81592. useInGammaSpace,
  81593. /**
  81594. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81595. */
  81596. usePMREMGenerator) {
  81597. if (noMipmap === void 0) { noMipmap = false; }
  81598. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81599. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81600. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81601. var _this = _super.call(this, name) || this;
  81602. _this.name = name;
  81603. _this.url = url;
  81604. _this.size = size;
  81605. _this.noMipmap = noMipmap;
  81606. _this.generateHarmonics = generateHarmonics;
  81607. _this.useInGammaSpace = useInGammaSpace;
  81608. _this.usePMREMGenerator = usePMREMGenerator;
  81609. return _this;
  81610. }
  81611. /**
  81612. * Execute the current task
  81613. * @param scene defines the scene where you want your assets to be loaded
  81614. * @param onSuccess is a callback called when the task is successfully executed
  81615. * @param onError is a callback called if an error occurs
  81616. */
  81617. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81618. var onload = function () {
  81619. onSuccess();
  81620. };
  81621. var onerror = function (message, exception) {
  81622. onError(message, exception);
  81623. };
  81624. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81625. };
  81626. return HDRCubeTextureAssetTask;
  81627. }(AbstractAssetTask));
  81628. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81629. /**
  81630. * This class can be used to easily import assets into a scene
  81631. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81632. */
  81633. var AssetsManager = /** @class */ (function () {
  81634. /**
  81635. * Creates a new AssetsManager
  81636. * @param scene defines the scene to work on
  81637. */
  81638. function AssetsManager(scene) {
  81639. this._isLoading = false;
  81640. this._tasks = new Array();
  81641. this._waitingTasksCount = 0;
  81642. this._totalTasksCount = 0;
  81643. /**
  81644. * Observable called when all tasks are processed
  81645. */
  81646. this.onTaskSuccessObservable = new BABYLON.Observable();
  81647. /**
  81648. * Observable called when a task had an error
  81649. */
  81650. this.onTaskErrorObservable = new BABYLON.Observable();
  81651. /**
  81652. * Observable called when a task is successful
  81653. */
  81654. this.onTasksDoneObservable = new BABYLON.Observable();
  81655. /**
  81656. * Observable called when a task is done (whatever the result is)
  81657. */
  81658. this.onProgressObservable = new BABYLON.Observable();
  81659. /**
  81660. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81661. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81662. */
  81663. this.useDefaultLoadingScreen = true;
  81664. this._scene = scene;
  81665. }
  81666. /**
  81667. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81668. * @param taskName defines the name of the new task
  81669. * @param meshesNames defines the name of meshes to load
  81670. * @param rootUrl defines the root url to use to locate files
  81671. * @param sceneFilename defines the filename of the scene file
  81672. * @returns a new {BABYLON.MeshAssetTask} object
  81673. */
  81674. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81675. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81676. this._tasks.push(task);
  81677. return task;
  81678. };
  81679. /**
  81680. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81681. * @param taskName defines the name of the new task
  81682. * @param url defines the url of the file to load
  81683. * @returns a new {BABYLON.TextFileAssetTask} object
  81684. */
  81685. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81686. var task = new TextFileAssetTask(taskName, url);
  81687. this._tasks.push(task);
  81688. return task;
  81689. };
  81690. /**
  81691. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81692. * @param taskName defines the name of the new task
  81693. * @param url defines the url of the file to load
  81694. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81695. */
  81696. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81697. var task = new BinaryFileAssetTask(taskName, url);
  81698. this._tasks.push(task);
  81699. return task;
  81700. };
  81701. /**
  81702. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81703. * @param taskName defines the name of the new task
  81704. * @param url defines the url of the file to load
  81705. * @returns a new {BABYLON.ImageAssetTask} object
  81706. */
  81707. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81708. var task = new ImageAssetTask(taskName, url);
  81709. this._tasks.push(task);
  81710. return task;
  81711. };
  81712. /**
  81713. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81714. * @param taskName defines the name of the new task
  81715. * @param url defines the url of the file to load
  81716. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81717. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81718. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81719. * @returns a new {BABYLON.TextureAssetTask} object
  81720. */
  81721. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81723. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81724. this._tasks.push(task);
  81725. return task;
  81726. };
  81727. /**
  81728. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81729. * @param taskName defines the name of the new task
  81730. * @param url defines the url of the file to load
  81731. * @param extensions defines the extension to use to load the cube map (can be null)
  81732. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81733. * @param files defines the list of files to load (can be null)
  81734. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81735. */
  81736. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81737. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81738. this._tasks.push(task);
  81739. return task;
  81740. };
  81741. /**
  81742. *
  81743. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81744. * @param taskName defines the name of the new task
  81745. * @param url defines the url of the file to load
  81746. * @param size defines the size you want for the cubemap (can be null)
  81747. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81748. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81749. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81750. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81751. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81752. */
  81753. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81754. if (noMipmap === void 0) { noMipmap = false; }
  81755. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81756. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81757. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81758. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81759. this._tasks.push(task);
  81760. return task;
  81761. };
  81762. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  81763. var _this = this;
  81764. this._waitingTasksCount--;
  81765. try {
  81766. if (task.taskState === AssetTaskState.DONE) {
  81767. // Let's remove successfull tasks
  81768. BABYLON.Tools.SetImmediate(function () {
  81769. var index = _this._tasks.indexOf(task);
  81770. if (index > -1) {
  81771. _this._tasks.splice(index, 1);
  81772. }
  81773. });
  81774. }
  81775. if (this.onProgress) {
  81776. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  81777. }
  81778. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  81779. }
  81780. catch (e) {
  81781. BABYLON.Tools.Error("Error running progress callbacks.");
  81782. console.log(e);
  81783. }
  81784. if (this._waitingTasksCount === 0) {
  81785. try {
  81786. if (this.onFinish) {
  81787. this.onFinish(this._tasks);
  81788. }
  81789. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81790. }
  81791. catch (e) {
  81792. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  81793. console.log(e);
  81794. }
  81795. this._isLoading = false;
  81796. this._scene.getEngine().hideLoadingUI();
  81797. }
  81798. };
  81799. AssetsManager.prototype._runTask = function (task) {
  81800. var _this = this;
  81801. var done = function () {
  81802. try {
  81803. if (_this.onTaskSuccess) {
  81804. _this.onTaskSuccess(task);
  81805. }
  81806. _this.onTaskSuccessObservable.notifyObservers(task);
  81807. _this._decreaseWaitingTasksCount(task);
  81808. }
  81809. catch (e) {
  81810. error("Error executing task success callbacks", e);
  81811. }
  81812. };
  81813. var error = function (message, exception) {
  81814. task._setErrorObject(message, exception);
  81815. if (_this.onTaskError) {
  81816. _this.onTaskError(task);
  81817. }
  81818. _this.onTaskErrorObservable.notifyObservers(task);
  81819. _this._decreaseWaitingTasksCount(task);
  81820. };
  81821. task.run(this._scene, done, error);
  81822. };
  81823. /**
  81824. * Reset the {BABYLON.AssetsManager} and remove all tasks
  81825. * @return the current instance of the {BABYLON.AssetsManager}
  81826. */
  81827. AssetsManager.prototype.reset = function () {
  81828. this._isLoading = false;
  81829. this._tasks = new Array();
  81830. return this;
  81831. };
  81832. /**
  81833. * Start the loading process
  81834. * @return the current instance of the {BABYLON.AssetsManager}
  81835. */
  81836. AssetsManager.prototype.load = function () {
  81837. if (this._isLoading) {
  81838. return this;
  81839. }
  81840. this._isLoading = true;
  81841. this._waitingTasksCount = this._tasks.length;
  81842. this._totalTasksCount = this._tasks.length;
  81843. if (this._waitingTasksCount === 0) {
  81844. if (this.onFinish) {
  81845. this.onFinish(this._tasks);
  81846. }
  81847. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81848. return this;
  81849. }
  81850. if (this.useDefaultLoadingScreen) {
  81851. this._scene.getEngine().displayLoadingUI();
  81852. }
  81853. for (var index = 0; index < this._tasks.length; index++) {
  81854. var task = this._tasks[index];
  81855. this._runTask(task);
  81856. }
  81857. return this;
  81858. };
  81859. return AssetsManager;
  81860. }());
  81861. BABYLON.AssetsManager = AssetsManager;
  81862. })(BABYLON || (BABYLON = {}));
  81863. //# sourceMappingURL=babylon.assetsManager.js.map
  81864. var BABYLON;
  81865. (function (BABYLON) {
  81866. var serializedGeometries = [];
  81867. var serializeGeometry = function (geometry, serializationGeometries) {
  81868. if (serializedGeometries[geometry.id]) {
  81869. return;
  81870. }
  81871. if (geometry.doNotSerialize) {
  81872. return;
  81873. }
  81874. if (geometry instanceof BABYLON.BoxGeometry) {
  81875. serializationGeometries.boxes.push(geometry.serialize());
  81876. }
  81877. else if (geometry instanceof BABYLON.SphereGeometry) {
  81878. serializationGeometries.spheres.push(geometry.serialize());
  81879. }
  81880. else if (geometry instanceof BABYLON.CylinderGeometry) {
  81881. serializationGeometries.cylinders.push(geometry.serialize());
  81882. }
  81883. else if (geometry instanceof BABYLON.TorusGeometry) {
  81884. serializationGeometries.toruses.push(geometry.serialize());
  81885. }
  81886. else if (geometry instanceof BABYLON.GroundGeometry) {
  81887. serializationGeometries.grounds.push(geometry.serialize());
  81888. }
  81889. else if (geometry instanceof BABYLON.Plane) {
  81890. serializationGeometries.planes.push(geometry.serialize());
  81891. }
  81892. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  81893. serializationGeometries.torusKnots.push(geometry.serialize());
  81894. }
  81895. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  81896. throw new Error("Unknown primitive type");
  81897. }
  81898. else {
  81899. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  81900. }
  81901. serializedGeometries[geometry.id] = true;
  81902. };
  81903. var serializeMesh = function (mesh, serializationScene) {
  81904. var serializationObject = {};
  81905. // Geometry
  81906. var geometry = mesh._geometry;
  81907. if (geometry) {
  81908. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  81909. // 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
  81910. serializeGeometry(geometry, serializationScene.geometries);
  81911. }
  81912. }
  81913. // Custom
  81914. if (mesh.serialize) {
  81915. mesh.serialize(serializationObject);
  81916. }
  81917. return serializationObject;
  81918. };
  81919. var finalizeSingleMesh = function (mesh, serializationObject) {
  81920. //only works if the mesh is already loaded
  81921. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81922. //serialize material
  81923. if (mesh.material) {
  81924. if (mesh.material instanceof BABYLON.StandardMaterial) {
  81925. serializationObject.materials = serializationObject.materials || [];
  81926. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81927. serializationObject.materials.push(mesh.material.serialize());
  81928. }
  81929. }
  81930. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  81931. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  81932. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81933. serializationObject.multiMaterials.push(mesh.material.serialize());
  81934. }
  81935. }
  81936. }
  81937. //serialize geometry
  81938. var geometry = mesh._geometry;
  81939. if (geometry) {
  81940. if (!serializationObject.geometries) {
  81941. serializationObject.geometries = {};
  81942. serializationObject.geometries.boxes = [];
  81943. serializationObject.geometries.spheres = [];
  81944. serializationObject.geometries.cylinders = [];
  81945. serializationObject.geometries.toruses = [];
  81946. serializationObject.geometries.grounds = [];
  81947. serializationObject.geometries.planes = [];
  81948. serializationObject.geometries.torusKnots = [];
  81949. serializationObject.geometries.vertexData = [];
  81950. }
  81951. serializeGeometry(geometry, serializationObject.geometries);
  81952. }
  81953. // Skeletons
  81954. if (mesh.skeleton) {
  81955. serializationObject.skeletons = serializationObject.skeletons || [];
  81956. serializationObject.skeletons.push(mesh.skeleton.serialize());
  81957. }
  81958. //serialize the actual mesh
  81959. serializationObject.meshes = serializationObject.meshes || [];
  81960. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81961. }
  81962. };
  81963. var SceneSerializer = /** @class */ (function () {
  81964. function SceneSerializer() {
  81965. }
  81966. SceneSerializer.ClearCache = function () {
  81967. serializedGeometries = [];
  81968. };
  81969. SceneSerializer.Serialize = function (scene) {
  81970. var serializationObject = {};
  81971. SceneSerializer.ClearCache();
  81972. // Scene
  81973. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  81974. serializationObject.autoClear = scene.autoClear;
  81975. serializationObject.clearColor = scene.clearColor.asArray();
  81976. serializationObject.ambientColor = scene.ambientColor.asArray();
  81977. serializationObject.gravity = scene.gravity.asArray();
  81978. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  81979. serializationObject.workerCollisions = scene.workerCollisions;
  81980. // Fog
  81981. if (scene.fogMode && scene.fogMode !== 0) {
  81982. serializationObject.fogMode = scene.fogMode;
  81983. serializationObject.fogColor = scene.fogColor.asArray();
  81984. serializationObject.fogStart = scene.fogStart;
  81985. serializationObject.fogEnd = scene.fogEnd;
  81986. serializationObject.fogDensity = scene.fogDensity;
  81987. }
  81988. //Physics
  81989. if (scene.isPhysicsEnabled()) {
  81990. var physicEngine = scene.getPhysicsEngine();
  81991. if (physicEngine) {
  81992. serializationObject.physicsEnabled = true;
  81993. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  81994. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  81995. }
  81996. }
  81997. // Metadata
  81998. if (scene.metadata) {
  81999. serializationObject.metadata = scene.metadata;
  82000. }
  82001. // Morph targets
  82002. serializationObject.morphTargetManagers = [];
  82003. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  82004. var abstractMesh = _a[_i];
  82005. var manager = abstractMesh.morphTargetManager;
  82006. if (manager) {
  82007. serializationObject.morphTargetManagers.push(manager.serialize());
  82008. }
  82009. }
  82010. // Lights
  82011. serializationObject.lights = [];
  82012. var index;
  82013. var light;
  82014. for (index = 0; index < scene.lights.length; index++) {
  82015. light = scene.lights[index];
  82016. if (!light.doNotSerialize) {
  82017. serializationObject.lights.push(light.serialize());
  82018. }
  82019. }
  82020. // Cameras
  82021. serializationObject.cameras = [];
  82022. for (index = 0; index < scene.cameras.length; index++) {
  82023. var camera = scene.cameras[index];
  82024. if (!camera.doNotSerialize) {
  82025. serializationObject.cameras.push(camera.serialize());
  82026. }
  82027. }
  82028. if (scene.activeCamera) {
  82029. serializationObject.activeCameraID = scene.activeCamera.id;
  82030. }
  82031. // Animations
  82032. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  82033. // Materials
  82034. serializationObject.materials = [];
  82035. serializationObject.multiMaterials = [];
  82036. var material;
  82037. for (index = 0; index < scene.materials.length; index++) {
  82038. material = scene.materials[index];
  82039. if (!material.doNotSerialize) {
  82040. serializationObject.materials.push(material.serialize());
  82041. }
  82042. }
  82043. // MultiMaterials
  82044. serializationObject.multiMaterials = [];
  82045. for (index = 0; index < scene.multiMaterials.length; index++) {
  82046. var multiMaterial = scene.multiMaterials[index];
  82047. serializationObject.multiMaterials.push(multiMaterial.serialize());
  82048. }
  82049. // Environment texture
  82050. if (scene.environmentTexture) {
  82051. serializationObject.environmentTexture = scene.environmentTexture.name;
  82052. }
  82053. // Skeletons
  82054. serializationObject.skeletons = [];
  82055. for (index = 0; index < scene.skeletons.length; index++) {
  82056. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  82057. }
  82058. // Transform nodes
  82059. serializationObject.transformNodes = [];
  82060. for (index = 0; index < scene.transformNodes.length; index++) {
  82061. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  82062. }
  82063. // Geometries
  82064. serializationObject.geometries = {};
  82065. serializationObject.geometries.boxes = [];
  82066. serializationObject.geometries.spheres = [];
  82067. serializationObject.geometries.cylinders = [];
  82068. serializationObject.geometries.toruses = [];
  82069. serializationObject.geometries.grounds = [];
  82070. serializationObject.geometries.planes = [];
  82071. serializationObject.geometries.torusKnots = [];
  82072. serializationObject.geometries.vertexData = [];
  82073. serializedGeometries = [];
  82074. var geometries = scene.getGeometries();
  82075. for (index = 0; index < geometries.length; index++) {
  82076. var geometry = geometries[index];
  82077. if (geometry.isReady()) {
  82078. serializeGeometry(geometry, serializationObject.geometries);
  82079. }
  82080. }
  82081. // Meshes
  82082. serializationObject.meshes = [];
  82083. for (index = 0; index < scene.meshes.length; index++) {
  82084. var abstractMesh = scene.meshes[index];
  82085. if (abstractMesh instanceof BABYLON.Mesh) {
  82086. var mesh = abstractMesh;
  82087. if (!mesh.doNotSerialize) {
  82088. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  82089. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  82090. }
  82091. }
  82092. }
  82093. }
  82094. // Particles Systems
  82095. serializationObject.particleSystems = [];
  82096. for (index = 0; index < scene.particleSystems.length; index++) {
  82097. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  82098. }
  82099. // Lens flares
  82100. serializationObject.lensFlareSystems = [];
  82101. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  82102. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  82103. }
  82104. // Shadows
  82105. serializationObject.shadowGenerators = [];
  82106. for (index = 0; index < scene.lights.length; index++) {
  82107. light = scene.lights[index];
  82108. var shadowGenerator = light.getShadowGenerator();
  82109. if (shadowGenerator) {
  82110. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  82111. }
  82112. }
  82113. // Action Manager
  82114. if (scene.actionManager) {
  82115. serializationObject.actions = scene.actionManager.serialize("scene");
  82116. }
  82117. // Audio
  82118. serializationObject.sounds = [];
  82119. for (index = 0; index < scene.soundTracks.length; index++) {
  82120. var soundtrack = scene.soundTracks[index];
  82121. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  82122. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  82123. }
  82124. }
  82125. return serializationObject;
  82126. };
  82127. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  82128. if (withParents === void 0) { withParents = false; }
  82129. if (withChildren === void 0) { withChildren = false; }
  82130. var serializationObject = {};
  82131. SceneSerializer.ClearCache();
  82132. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  82133. if (withParents || withChildren) {
  82134. //deliberate for loop! not for each, appended should be processed as well.
  82135. for (var i = 0; i < toSerialize.length; ++i) {
  82136. if (withChildren) {
  82137. toSerialize[i].getDescendants().forEach(function (node) {
  82138. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  82139. toSerialize.push(node);
  82140. }
  82141. });
  82142. }
  82143. //make sure the array doesn't contain the object already
  82144. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  82145. toSerialize.push(toSerialize[i].parent);
  82146. }
  82147. }
  82148. }
  82149. toSerialize.forEach(function (mesh) {
  82150. finalizeSingleMesh(mesh, serializationObject);
  82151. });
  82152. return serializationObject;
  82153. };
  82154. return SceneSerializer;
  82155. }());
  82156. BABYLON.SceneSerializer = SceneSerializer;
  82157. })(BABYLON || (BABYLON = {}));
  82158. //# sourceMappingURL=babylon.sceneSerializer.js.map
  82159. var BABYLON;
  82160. (function (BABYLON) {
  82161. var ReflectionProbe = /** @class */ (function () {
  82162. function ReflectionProbe(name, size, scene, generateMipMaps) {
  82163. if (generateMipMaps === void 0) { generateMipMaps = true; }
  82164. var _this = this;
  82165. this.name = name;
  82166. this._viewMatrix = BABYLON.Matrix.Identity();
  82167. this._target = BABYLON.Vector3.Zero();
  82168. this._add = BABYLON.Vector3.Zero();
  82169. this.invertYAxis = false;
  82170. this.position = BABYLON.Vector3.Zero();
  82171. this._scene = scene;
  82172. this._scene.reflectionProbes.push(this);
  82173. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  82174. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  82175. switch (faceIndex) {
  82176. case 0:
  82177. _this._add.copyFromFloats(1, 0, 0);
  82178. break;
  82179. case 1:
  82180. _this._add.copyFromFloats(-1, 0, 0);
  82181. break;
  82182. case 2:
  82183. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  82184. break;
  82185. case 3:
  82186. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  82187. break;
  82188. case 4:
  82189. _this._add.copyFromFloats(0, 0, 1);
  82190. break;
  82191. case 5:
  82192. _this._add.copyFromFloats(0, 0, -1);
  82193. break;
  82194. }
  82195. if (_this._attachedMesh) {
  82196. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  82197. }
  82198. _this.position.addToRef(_this._add, _this._target);
  82199. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  82200. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  82201. scene._forcedViewPosition = _this.position;
  82202. });
  82203. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  82204. scene._forcedViewPosition = null;
  82205. scene.updateTransformMatrix(true);
  82206. });
  82207. if (scene.activeCamera) {
  82208. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82209. }
  82210. }
  82211. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  82212. get: function () {
  82213. return this._renderTargetTexture.samples;
  82214. },
  82215. set: function (value) {
  82216. this._renderTargetTexture.samples = value;
  82217. },
  82218. enumerable: true,
  82219. configurable: true
  82220. });
  82221. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  82222. get: function () {
  82223. return this._renderTargetTexture.refreshRate;
  82224. },
  82225. set: function (value) {
  82226. this._renderTargetTexture.refreshRate = value;
  82227. },
  82228. enumerable: true,
  82229. configurable: true
  82230. });
  82231. ReflectionProbe.prototype.getScene = function () {
  82232. return this._scene;
  82233. };
  82234. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  82235. get: function () {
  82236. return this._renderTargetTexture;
  82237. },
  82238. enumerable: true,
  82239. configurable: true
  82240. });
  82241. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  82242. get: function () {
  82243. return this._renderTargetTexture.renderList;
  82244. },
  82245. enumerable: true,
  82246. configurable: true
  82247. });
  82248. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  82249. this._attachedMesh = mesh;
  82250. };
  82251. /**
  82252. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  82253. *
  82254. * @param renderingGroupId The rendering group id corresponding to its index
  82255. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  82256. */
  82257. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  82258. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  82259. };
  82260. ReflectionProbe.prototype.dispose = function () {
  82261. var index = this._scene.reflectionProbes.indexOf(this);
  82262. if (index !== -1) {
  82263. // Remove from the scene if found
  82264. this._scene.reflectionProbes.splice(index, 1);
  82265. }
  82266. if (this._renderTargetTexture) {
  82267. this._renderTargetTexture.dispose();
  82268. this._renderTargetTexture = null;
  82269. }
  82270. };
  82271. return ReflectionProbe;
  82272. }());
  82273. BABYLON.ReflectionProbe = ReflectionProbe;
  82274. })(BABYLON || (BABYLON = {}));
  82275. //# sourceMappingURL=babylon.reflectionProbe.js.map
  82276. var BABYLON;
  82277. (function (BABYLON) {
  82278. var Layer = /** @class */ (function () {
  82279. function Layer(name, imgUrl, scene, isBackground, color) {
  82280. this.name = name;
  82281. this.scale = new BABYLON.Vector2(1, 1);
  82282. this.offset = new BABYLON.Vector2(0, 0);
  82283. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  82284. this.layerMask = 0x0FFFFFFF;
  82285. this._vertexBuffers = {};
  82286. // Events
  82287. /**
  82288. * An event triggered when the layer is disposed.
  82289. * @type {BABYLON.Observable}
  82290. */
  82291. this.onDisposeObservable = new BABYLON.Observable();
  82292. /**
  82293. * An event triggered before rendering the scene
  82294. * @type {BABYLON.Observable}
  82295. */
  82296. this.onBeforeRenderObservable = new BABYLON.Observable();
  82297. /**
  82298. * An event triggered after rendering the scene
  82299. * @type {BABYLON.Observable}
  82300. */
  82301. this.onAfterRenderObservable = new BABYLON.Observable();
  82302. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  82303. this.isBackground = isBackground === undefined ? true : isBackground;
  82304. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  82305. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  82306. this._scene.layers.push(this);
  82307. var engine = this._scene.getEngine();
  82308. // VBO
  82309. var vertices = [];
  82310. vertices.push(1, 1);
  82311. vertices.push(-1, 1);
  82312. vertices.push(-1, -1);
  82313. vertices.push(1, -1);
  82314. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82315. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82316. this._createIndexBuffer();
  82317. // Effects
  82318. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  82319. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  82320. }
  82321. Object.defineProperty(Layer.prototype, "onDispose", {
  82322. set: function (callback) {
  82323. if (this._onDisposeObserver) {
  82324. this.onDisposeObservable.remove(this._onDisposeObserver);
  82325. }
  82326. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82327. },
  82328. enumerable: true,
  82329. configurable: true
  82330. });
  82331. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  82332. set: function (callback) {
  82333. if (this._onBeforeRenderObserver) {
  82334. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  82335. }
  82336. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  82337. },
  82338. enumerable: true,
  82339. configurable: true
  82340. });
  82341. Object.defineProperty(Layer.prototype, "onAfterRender", {
  82342. set: function (callback) {
  82343. if (this._onAfterRenderObserver) {
  82344. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82345. }
  82346. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  82347. },
  82348. enumerable: true,
  82349. configurable: true
  82350. });
  82351. Layer.prototype._createIndexBuffer = function () {
  82352. var engine = this._scene.getEngine();
  82353. // Indices
  82354. var indices = [];
  82355. indices.push(0);
  82356. indices.push(1);
  82357. indices.push(2);
  82358. indices.push(0);
  82359. indices.push(2);
  82360. indices.push(3);
  82361. this._indexBuffer = engine.createIndexBuffer(indices);
  82362. };
  82363. Layer.prototype._rebuild = function () {
  82364. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82365. if (vb) {
  82366. vb._rebuild();
  82367. }
  82368. this._createIndexBuffer();
  82369. };
  82370. Layer.prototype.render = function () {
  82371. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  82372. // Check
  82373. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  82374. return;
  82375. var engine = this._scene.getEngine();
  82376. this.onBeforeRenderObservable.notifyObservers(this);
  82377. // Render
  82378. engine.enableEffect(currentEffect);
  82379. engine.setState(false);
  82380. // Texture
  82381. currentEffect.setTexture("textureSampler", this.texture);
  82382. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  82383. // Color
  82384. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  82385. // Scale / offset
  82386. currentEffect.setVector2("offset", this.offset);
  82387. currentEffect.setVector2("scale", this.scale);
  82388. // VBOs
  82389. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82390. // Draw order
  82391. if (!this.alphaTest) {
  82392. engine.setAlphaMode(this.alphaBlendingMode);
  82393. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82394. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82395. }
  82396. else {
  82397. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82398. }
  82399. this.onAfterRenderObservable.notifyObservers(this);
  82400. };
  82401. Layer.prototype.dispose = function () {
  82402. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82403. if (vertexBuffer) {
  82404. vertexBuffer.dispose();
  82405. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82406. }
  82407. if (this._indexBuffer) {
  82408. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82409. this._indexBuffer = null;
  82410. }
  82411. if (this.texture) {
  82412. this.texture.dispose();
  82413. this.texture = null;
  82414. }
  82415. // Remove from scene
  82416. var index = this._scene.layers.indexOf(this);
  82417. this._scene.layers.splice(index, 1);
  82418. // Callback
  82419. this.onDisposeObservable.notifyObservers(this);
  82420. this.onDisposeObservable.clear();
  82421. this.onAfterRenderObservable.clear();
  82422. this.onBeforeRenderObservable.clear();
  82423. };
  82424. return Layer;
  82425. }());
  82426. BABYLON.Layer = Layer;
  82427. })(BABYLON || (BABYLON = {}));
  82428. //# sourceMappingURL=babylon.layer.js.map
  82429. var BABYLON;
  82430. (function (BABYLON) {
  82431. var TextureTools = /** @class */ (function () {
  82432. function TextureTools() {
  82433. }
  82434. /**
  82435. * Uses the GPU to create a copy texture rescaled at a given size
  82436. * @param texture Texture to copy from
  82437. * @param width Desired width
  82438. * @param height Desired height
  82439. * @return Generated texture
  82440. */
  82441. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  82442. if (useBilinearMode === void 0) { useBilinearMode = true; }
  82443. var scene = texture.getScene();
  82444. var engine = scene.getEngine();
  82445. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  82446. rtt.wrapU = texture.wrapU;
  82447. rtt.wrapV = texture.wrapV;
  82448. rtt.uOffset = texture.uOffset;
  82449. rtt.vOffset = texture.vOffset;
  82450. rtt.uScale = texture.uScale;
  82451. rtt.vScale = texture.vScale;
  82452. rtt.uAng = texture.uAng;
  82453. rtt.vAng = texture.vAng;
  82454. rtt.wAng = texture.wAng;
  82455. rtt.coordinatesIndex = texture.coordinatesIndex;
  82456. rtt.level = texture.level;
  82457. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82458. rtt._texture.isReady = false;
  82459. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82460. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82461. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82462. passPostProcess.getEffect().executeWhenCompiled(function () {
  82463. passPostProcess.onApply = function (effect) {
  82464. effect.setTexture("textureSampler", texture);
  82465. };
  82466. var internalTexture = rtt.getInternalTexture();
  82467. if (internalTexture) {
  82468. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82469. engine.unBindFramebuffer(internalTexture);
  82470. rtt.disposeFramebufferObjects();
  82471. passPostProcess.dispose();
  82472. internalTexture.isReady = true;
  82473. }
  82474. });
  82475. return rtt;
  82476. };
  82477. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82478. if (!scene._environmentBRDFTexture) {
  82479. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82480. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82481. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82482. scene._environmentBRDFTexture = texture;
  82483. }
  82484. return scene._environmentBRDFTexture;
  82485. };
  82486. 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=";
  82487. return TextureTools;
  82488. }());
  82489. BABYLON.TextureTools = TextureTools;
  82490. })(BABYLON || (BABYLON = {}));
  82491. //# sourceMappingURL=babylon.textureTools.js.map
  82492. var BABYLON;
  82493. (function (BABYLON) {
  82494. var FramingBehavior = /** @class */ (function () {
  82495. function FramingBehavior() {
  82496. this._mode = FramingBehavior.FitFrustumSidesMode;
  82497. this._radiusScale = 1.0;
  82498. this._positionScale = 0.5;
  82499. this._defaultElevation = 0.3;
  82500. this._elevationReturnTime = 1500;
  82501. this._elevationReturnWaitTime = 1000;
  82502. this._zoomStopsAnimation = false;
  82503. this._framingTime = 1500;
  82504. this._isPointerDown = false;
  82505. this._lastInteractionTime = -Infinity;
  82506. // Framing control
  82507. this._animatables = new Array();
  82508. this._betaIsAnimating = false;
  82509. }
  82510. Object.defineProperty(FramingBehavior.prototype, "name", {
  82511. get: function () {
  82512. return "Framing";
  82513. },
  82514. enumerable: true,
  82515. configurable: true
  82516. });
  82517. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82518. /**
  82519. * Gets current mode used by the behavior.
  82520. */
  82521. get: function () {
  82522. return this._mode;
  82523. },
  82524. /**
  82525. * Sets the current mode used by the behavior
  82526. */
  82527. set: function (mode) {
  82528. this._mode = mode;
  82529. },
  82530. enumerable: true,
  82531. configurable: true
  82532. });
  82533. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82534. /**
  82535. * Gets the scale applied to the radius
  82536. */
  82537. get: function () {
  82538. return this._radiusScale;
  82539. },
  82540. /**
  82541. * Sets the scale applied to the radius (1 by default)
  82542. */
  82543. set: function (radius) {
  82544. this._radiusScale = radius;
  82545. },
  82546. enumerable: true,
  82547. configurable: true
  82548. });
  82549. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82550. /**
  82551. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82552. */
  82553. get: function () {
  82554. return this._positionScale;
  82555. },
  82556. /**
  82557. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82558. */
  82559. set: function (scale) {
  82560. this._positionScale = scale;
  82561. },
  82562. enumerable: true,
  82563. configurable: true
  82564. });
  82565. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82566. /**
  82567. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82568. * behaviour is triggered, in radians.
  82569. */
  82570. get: function () {
  82571. return this._defaultElevation;
  82572. },
  82573. /**
  82574. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82575. * behaviour is triggered, in radians.
  82576. */
  82577. set: function (elevation) {
  82578. this._defaultElevation = elevation;
  82579. },
  82580. enumerable: true,
  82581. configurable: true
  82582. });
  82583. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82584. /**
  82585. * Gets the time (in milliseconds) taken to return to the default beta position.
  82586. * Negative value indicates camera should not return to default.
  82587. */
  82588. get: function () {
  82589. return this._elevationReturnTime;
  82590. },
  82591. /**
  82592. * Sets the time (in milliseconds) taken to return to the default beta position.
  82593. * Negative value indicates camera should not return to default.
  82594. */
  82595. set: function (speed) {
  82596. this._elevationReturnTime = speed;
  82597. },
  82598. enumerable: true,
  82599. configurable: true
  82600. });
  82601. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82602. /**
  82603. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82604. */
  82605. get: function () {
  82606. return this._elevationReturnWaitTime;
  82607. },
  82608. /**
  82609. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82610. */
  82611. set: function (time) {
  82612. this._elevationReturnWaitTime = time;
  82613. },
  82614. enumerable: true,
  82615. configurable: true
  82616. });
  82617. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82618. /**
  82619. * Gets the flag that indicates if user zooming should stop animation.
  82620. */
  82621. get: function () {
  82622. return this._zoomStopsAnimation;
  82623. },
  82624. /**
  82625. * Sets the flag that indicates if user zooming should stop animation.
  82626. */
  82627. set: function (flag) {
  82628. this._zoomStopsAnimation = flag;
  82629. },
  82630. enumerable: true,
  82631. configurable: true
  82632. });
  82633. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82634. /**
  82635. * Gets the transition time when framing the mesh, in milliseconds
  82636. */
  82637. get: function () {
  82638. return this._framingTime;
  82639. },
  82640. /**
  82641. * Sets the transition time when framing the mesh, in milliseconds
  82642. */
  82643. set: function (time) {
  82644. this._framingTime = time;
  82645. },
  82646. enumerable: true,
  82647. configurable: true
  82648. });
  82649. FramingBehavior.prototype.init = function () {
  82650. // Do notihng
  82651. };
  82652. FramingBehavior.prototype.attach = function (camera) {
  82653. var _this = this;
  82654. this._attachedCamera = camera;
  82655. var scene = this._attachedCamera.getScene();
  82656. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82657. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82658. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82659. _this._isPointerDown = true;
  82660. return;
  82661. }
  82662. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82663. _this._isPointerDown = false;
  82664. }
  82665. });
  82666. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82667. if (mesh) {
  82668. _this.zoomOnMesh(mesh);
  82669. }
  82670. });
  82671. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82672. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82673. _this._applyUserInteraction();
  82674. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82675. // back to the default position after a given timeout
  82676. _this._maintainCameraAboveGround();
  82677. });
  82678. };
  82679. FramingBehavior.prototype.detach = function () {
  82680. if (!this._attachedCamera) {
  82681. return;
  82682. }
  82683. var scene = this._attachedCamera.getScene();
  82684. if (this._onPrePointerObservableObserver) {
  82685. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82686. }
  82687. if (this._onAfterCheckInputsObserver) {
  82688. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82689. }
  82690. if (this._onMeshTargetChangedObserver) {
  82691. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82692. }
  82693. this._attachedCamera = null;
  82694. };
  82695. /**
  82696. * Targets the given mesh and updates zoom level accordingly.
  82697. * @param mesh The mesh to target.
  82698. * @param radius Optional. If a cached radius position already exists, overrides default.
  82699. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82700. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82701. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82702. */
  82703. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82704. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82705. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82706. mesh.computeWorldMatrix(true);
  82707. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82708. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82709. };
  82710. /**
  82711. * Targets the given mesh with its children and updates zoom level accordingly.
  82712. * @param mesh The mesh to target.
  82713. * @param radius Optional. If a cached radius position already exists, overrides default.
  82714. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82715. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82716. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82717. */
  82718. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82719. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82720. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82721. mesh.computeWorldMatrix(true);
  82722. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82723. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82724. };
  82725. /**
  82726. * Targets the given meshes with their children and updates zoom level accordingly.
  82727. * @param meshes The mesh to target.
  82728. * @param radius Optional. If a cached radius position already exists, overrides default.
  82729. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82730. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82731. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82732. */
  82733. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82734. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82735. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82736. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82737. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82738. for (var i = 0; i < meshes.length; i++) {
  82739. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82740. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82741. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82742. }
  82743. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82744. };
  82745. /**
  82746. * Targets the given mesh and updates zoom level accordingly.
  82747. * @param mesh The mesh to target.
  82748. * @param radius Optional. If a cached radius position already exists, overrides default.
  82749. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82750. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82751. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82752. */
  82753. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82754. var _this = this;
  82755. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82756. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82757. var zoomTarget;
  82758. if (!this._attachedCamera) {
  82759. return;
  82760. }
  82761. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  82762. var bottom = minimumWorld.y;
  82763. var top = maximumWorld.y;
  82764. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  82765. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  82766. if (focusOnOriginXZ) {
  82767. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  82768. }
  82769. else {
  82770. var centerWorld = minimumWorld.add(radiusWorld);
  82771. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  82772. }
  82773. if (!this._vectorTransition) {
  82774. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  82775. }
  82776. this._betaIsAnimating = true;
  82777. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  82778. if (animatable) {
  82779. this._animatables.push(animatable);
  82780. }
  82781. // sets the radius and lower radius bounds
  82782. // Small delta ensures camera is not always at lower zoom limit.
  82783. var radius = 0;
  82784. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  82785. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82786. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  82787. radius = position;
  82788. }
  82789. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82790. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82791. if (this._attachedCamera.lowerRadiusLimit === null) {
  82792. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  82793. }
  82794. }
  82795. // Set sensibilities
  82796. var extend = maximumWorld.subtract(minimumWorld).length();
  82797. this._attachedCamera.panningSensibility = 5000 / extend;
  82798. this._attachedCamera.wheelPrecision = 100 / radius;
  82799. // transition to new radius
  82800. if (!this._radiusTransition) {
  82801. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82802. }
  82803. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  82804. if (onAnimationEnd) {
  82805. onAnimationEnd();
  82806. }
  82807. if (_this._attachedCamera) {
  82808. _this._attachedCamera.storeState();
  82809. }
  82810. });
  82811. if (animatable) {
  82812. this._animatables.push(animatable);
  82813. }
  82814. };
  82815. /**
  82816. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  82817. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  82818. * frustum width.
  82819. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  82820. * to fully enclose the mesh in the viewing frustum.
  82821. */
  82822. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  82823. var size = maximumWorld.subtract(minimumWorld);
  82824. var boxVectorGlobalDiagonal = size.length();
  82825. var frustumSlope = this._getFrustumSlope();
  82826. // Formula for setting distance
  82827. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  82828. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  82829. // Horizon distance
  82830. var radius = radiusWithoutFraming * this._radiusScale;
  82831. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  82832. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  82833. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  82834. var camera = this._attachedCamera;
  82835. if (!camera) {
  82836. return 0;
  82837. }
  82838. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82839. // Don't exceed the requested limit
  82840. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  82841. }
  82842. // Don't exceed the upper radius limit
  82843. if (camera.upperRadiusLimit) {
  82844. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  82845. }
  82846. return distance;
  82847. };
  82848. /**
  82849. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  82850. * is automatically returned to its default position (expected to be above ground plane).
  82851. */
  82852. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  82853. var _this = this;
  82854. if (this._elevationReturnTime < 0) {
  82855. return;
  82856. }
  82857. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  82858. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  82859. var limitBeta = Math.PI * 0.5;
  82860. // Bring the camera back up if below the ground plane
  82861. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  82862. this._betaIsAnimating = true;
  82863. //Transition to new position
  82864. this.stopAllAnimations();
  82865. if (!this._betaTransition) {
  82866. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82867. }
  82868. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  82869. _this._clearAnimationLocks();
  82870. _this.stopAllAnimations();
  82871. });
  82872. if (animatabe) {
  82873. this._animatables.push(animatabe);
  82874. }
  82875. }
  82876. };
  82877. /**
  82878. * Returns the frustum slope based on the canvas ratio and camera FOV
  82879. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  82880. */
  82881. FramingBehavior.prototype._getFrustumSlope = function () {
  82882. // Calculate the viewport ratio
  82883. // Aspect Ratio is Height/Width.
  82884. var camera = this._attachedCamera;
  82885. if (!camera) {
  82886. return BABYLON.Vector2.Zero();
  82887. }
  82888. var engine = camera.getScene().getEngine();
  82889. var aspectRatio = engine.getAspectRatio(camera);
  82890. // Camera FOV is the vertical field of view (top-bottom) in radians.
  82891. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  82892. var frustumSlopeY = Math.tan(camera.fov / 2);
  82893. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  82894. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  82895. // along the forward vector.
  82896. var frustumSlopeX = frustumSlopeY * aspectRatio;
  82897. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  82898. };
  82899. /**
  82900. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  82901. */
  82902. FramingBehavior.prototype._clearAnimationLocks = function () {
  82903. this._betaIsAnimating = false;
  82904. };
  82905. /**
  82906. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82907. */
  82908. FramingBehavior.prototype._applyUserInteraction = function () {
  82909. if (this.isUserIsMoving) {
  82910. this._lastInteractionTime = BABYLON.Tools.Now;
  82911. this.stopAllAnimations();
  82912. this._clearAnimationLocks();
  82913. }
  82914. };
  82915. /**
  82916. * Stops and removes all animations that have been applied to the camera
  82917. */
  82918. FramingBehavior.prototype.stopAllAnimations = function () {
  82919. if (this._attachedCamera) {
  82920. this._attachedCamera.animations = [];
  82921. }
  82922. while (this._animatables.length) {
  82923. if (this._animatables[0]) {
  82924. this._animatables[0].onAnimationEnd = null;
  82925. this._animatables[0].stop();
  82926. }
  82927. this._animatables.shift();
  82928. }
  82929. };
  82930. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  82931. /**
  82932. * Gets a value indicating if the user is moving the camera
  82933. */
  82934. get: function () {
  82935. if (!this._attachedCamera) {
  82936. return false;
  82937. }
  82938. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82939. this._attachedCamera.inertialBetaOffset !== 0 ||
  82940. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82941. this._attachedCamera.inertialPanningX !== 0 ||
  82942. this._attachedCamera.inertialPanningY !== 0 ||
  82943. this._isPointerDown;
  82944. },
  82945. enumerable: true,
  82946. configurable: true
  82947. });
  82948. /**
  82949. * The easing function used by animations
  82950. */
  82951. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  82952. /**
  82953. * The easing mode used by animations
  82954. */
  82955. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  82956. // Statics
  82957. /**
  82958. * The camera can move all the way towards the mesh.
  82959. */
  82960. FramingBehavior.IgnoreBoundsSizeMode = 0;
  82961. /**
  82962. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  82963. */
  82964. FramingBehavior.FitFrustumSidesMode = 1;
  82965. return FramingBehavior;
  82966. }());
  82967. BABYLON.FramingBehavior = FramingBehavior;
  82968. })(BABYLON || (BABYLON = {}));
  82969. //# sourceMappingURL=babylon.framingBehavior.js.map
  82970. var BABYLON;
  82971. (function (BABYLON) {
  82972. /**
  82973. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  82974. */
  82975. var BouncingBehavior = /** @class */ (function () {
  82976. function BouncingBehavior() {
  82977. /**
  82978. * The duration of the animation, in milliseconds
  82979. */
  82980. this.transitionDuration = 450;
  82981. /**
  82982. * Length of the distance animated by the transition when lower radius is reached
  82983. */
  82984. this.lowerRadiusTransitionRange = 2;
  82985. /**
  82986. * Length of the distance animated by the transition when upper radius is reached
  82987. */
  82988. this.upperRadiusTransitionRange = -2;
  82989. this._autoTransitionRange = false;
  82990. // Animations
  82991. this._radiusIsAnimating = false;
  82992. this._radiusBounceTransition = null;
  82993. this._animatables = new Array();
  82994. }
  82995. Object.defineProperty(BouncingBehavior.prototype, "name", {
  82996. get: function () {
  82997. return "Bouncing";
  82998. },
  82999. enumerable: true,
  83000. configurable: true
  83001. });
  83002. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  83003. /**
  83004. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  83005. */
  83006. get: function () {
  83007. return this._autoTransitionRange;
  83008. },
  83009. /**
  83010. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  83011. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  83012. */
  83013. set: function (value) {
  83014. var _this = this;
  83015. if (this._autoTransitionRange === value) {
  83016. return;
  83017. }
  83018. this._autoTransitionRange = value;
  83019. var camera = this._attachedCamera;
  83020. if (!camera) {
  83021. return;
  83022. }
  83023. if (value) {
  83024. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  83025. if (!mesh) {
  83026. return;
  83027. }
  83028. mesh.computeWorldMatrix(true);
  83029. var diagonal = mesh.getBoundingInfo().diagonalLength;
  83030. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  83031. _this.upperRadiusTransitionRange = diagonal * 0.05;
  83032. });
  83033. }
  83034. else if (this._onMeshTargetChangedObserver) {
  83035. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83036. }
  83037. },
  83038. enumerable: true,
  83039. configurable: true
  83040. });
  83041. BouncingBehavior.prototype.init = function () {
  83042. // Do notihng
  83043. };
  83044. BouncingBehavior.prototype.attach = function (camera) {
  83045. var _this = this;
  83046. this._attachedCamera = camera;
  83047. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83048. if (!_this._attachedCamera) {
  83049. return;
  83050. }
  83051. // Add the bounce animation to the lower radius limit
  83052. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  83053. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  83054. }
  83055. // Add the bounce animation to the upper radius limit
  83056. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  83057. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  83058. }
  83059. });
  83060. };
  83061. BouncingBehavior.prototype.detach = function () {
  83062. if (!this._attachedCamera) {
  83063. return;
  83064. }
  83065. if (this._onAfterCheckInputsObserver) {
  83066. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83067. }
  83068. if (this._onMeshTargetChangedObserver) {
  83069. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83070. }
  83071. this._attachedCamera = null;
  83072. };
  83073. /**
  83074. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  83075. * @param radiusLimit The limit to check against.
  83076. * @return Bool to indicate if at limit.
  83077. */
  83078. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  83079. if (!this._attachedCamera) {
  83080. return false;
  83081. }
  83082. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  83083. return true;
  83084. }
  83085. return false;
  83086. };
  83087. /**
  83088. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  83089. * @param radiusDelta The delta by which to animate to. Can be negative.
  83090. */
  83091. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  83092. var _this = this;
  83093. if (!this._attachedCamera) {
  83094. return;
  83095. }
  83096. if (!this._radiusBounceTransition) {
  83097. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  83098. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  83099. }
  83100. // Prevent zoom until bounce has completed
  83101. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  83102. this._attachedCamera.wheelPrecision = Infinity;
  83103. this._attachedCamera.inertialRadiusOffset = 0;
  83104. // Animate to the radius limit
  83105. this.stopAllAnimations();
  83106. this._radiusIsAnimating = true;
  83107. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  83108. if (animatable) {
  83109. this._animatables.push(animatable);
  83110. }
  83111. };
  83112. /**
  83113. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  83114. */
  83115. BouncingBehavior.prototype._clearAnimationLocks = function () {
  83116. this._radiusIsAnimating = false;
  83117. if (this._attachedCamera) {
  83118. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  83119. }
  83120. };
  83121. /**
  83122. * Stops and removes all animations that have been applied to the camera
  83123. */
  83124. BouncingBehavior.prototype.stopAllAnimations = function () {
  83125. if (this._attachedCamera) {
  83126. this._attachedCamera.animations = [];
  83127. }
  83128. while (this._animatables.length) {
  83129. this._animatables[0].onAnimationEnd = null;
  83130. this._animatables[0].stop();
  83131. this._animatables.shift();
  83132. }
  83133. };
  83134. /**
  83135. * The easing function used by animations
  83136. */
  83137. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  83138. /**
  83139. * The easing mode used by animations
  83140. */
  83141. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  83142. return BouncingBehavior;
  83143. }());
  83144. BABYLON.BouncingBehavior = BouncingBehavior;
  83145. })(BABYLON || (BABYLON = {}));
  83146. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  83147. var BABYLON;
  83148. (function (BABYLON) {
  83149. var AutoRotationBehavior = /** @class */ (function () {
  83150. function AutoRotationBehavior() {
  83151. this._zoomStopsAnimation = false;
  83152. this._idleRotationSpeed = 0.05;
  83153. this._idleRotationWaitTime = 2000;
  83154. this._idleRotationSpinupTime = 2000;
  83155. this._isPointerDown = false;
  83156. this._lastFrameTime = null;
  83157. this._lastInteractionTime = -Infinity;
  83158. this._cameraRotationSpeed = 0;
  83159. this._lastFrameRadius = 0;
  83160. }
  83161. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  83162. get: function () {
  83163. return "AutoRotation";
  83164. },
  83165. enumerable: true,
  83166. configurable: true
  83167. });
  83168. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  83169. /**
  83170. * Gets the flag that indicates if user zooming should stop animation.
  83171. */
  83172. get: function () {
  83173. return this._zoomStopsAnimation;
  83174. },
  83175. /**
  83176. * Sets the flag that indicates if user zooming should stop animation.
  83177. */
  83178. set: function (flag) {
  83179. this._zoomStopsAnimation = flag;
  83180. },
  83181. enumerable: true,
  83182. configurable: true
  83183. });
  83184. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  83185. /**
  83186. * Gets the default speed at which the camera rotates around the model.
  83187. */
  83188. get: function () {
  83189. return this._idleRotationSpeed;
  83190. },
  83191. /**
  83192. * Sets the default speed at which the camera rotates around the model.
  83193. */
  83194. set: function (speed) {
  83195. this._idleRotationSpeed = speed;
  83196. },
  83197. enumerable: true,
  83198. configurable: true
  83199. });
  83200. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  83201. /**
  83202. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  83203. */
  83204. get: function () {
  83205. return this._idleRotationWaitTime;
  83206. },
  83207. /**
  83208. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  83209. */
  83210. set: function (time) {
  83211. this._idleRotationWaitTime = time;
  83212. },
  83213. enumerable: true,
  83214. configurable: true
  83215. });
  83216. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  83217. /**
  83218. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83219. */
  83220. get: function () {
  83221. return this._idleRotationSpinupTime;
  83222. },
  83223. /**
  83224. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83225. */
  83226. set: function (time) {
  83227. this._idleRotationSpinupTime = time;
  83228. },
  83229. enumerable: true,
  83230. configurable: true
  83231. });
  83232. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  83233. /**
  83234. * Gets a value indicating if the camera is currently rotating because of this behavior
  83235. */
  83236. get: function () {
  83237. return Math.abs(this._cameraRotationSpeed) > 0;
  83238. },
  83239. enumerable: true,
  83240. configurable: true
  83241. });
  83242. AutoRotationBehavior.prototype.init = function () {
  83243. // Do notihng
  83244. };
  83245. AutoRotationBehavior.prototype.attach = function (camera) {
  83246. var _this = this;
  83247. this._attachedCamera = camera;
  83248. var scene = this._attachedCamera.getScene();
  83249. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  83250. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  83251. _this._isPointerDown = true;
  83252. return;
  83253. }
  83254. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  83255. _this._isPointerDown = false;
  83256. }
  83257. });
  83258. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83259. var now = BABYLON.Tools.Now;
  83260. var dt = 0;
  83261. if (_this._lastFrameTime != null) {
  83262. dt = now - _this._lastFrameTime;
  83263. }
  83264. _this._lastFrameTime = now;
  83265. // Stop the animation if there is user interaction and the animation should stop for this interaction
  83266. _this._applyUserInteraction();
  83267. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  83268. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  83269. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  83270. // Step camera rotation by rotation speed
  83271. if (_this._attachedCamera) {
  83272. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  83273. }
  83274. });
  83275. };
  83276. AutoRotationBehavior.prototype.detach = function () {
  83277. if (!this._attachedCamera) {
  83278. return;
  83279. }
  83280. var scene = this._attachedCamera.getScene();
  83281. if (this._onPrePointerObservableObserver) {
  83282. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  83283. }
  83284. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83285. this._attachedCamera = null;
  83286. };
  83287. /**
  83288. * Returns true if user is scrolling.
  83289. * @return true if user is scrolling.
  83290. */
  83291. AutoRotationBehavior.prototype._userIsZooming = function () {
  83292. if (!this._attachedCamera) {
  83293. return false;
  83294. }
  83295. return this._attachedCamera.inertialRadiusOffset !== 0;
  83296. };
  83297. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  83298. if (!this._attachedCamera) {
  83299. return false;
  83300. }
  83301. var zoomHasHitLimit = false;
  83302. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  83303. zoomHasHitLimit = true;
  83304. }
  83305. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  83306. this._lastFrameRadius = this._attachedCamera.radius;
  83307. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  83308. };
  83309. /**
  83310. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  83311. */
  83312. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  83313. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  83314. this._lastInteractionTime = BABYLON.Tools.Now;
  83315. }
  83316. };
  83317. // Tools
  83318. AutoRotationBehavior.prototype._userIsMoving = function () {
  83319. if (!this._attachedCamera) {
  83320. return false;
  83321. }
  83322. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  83323. this._attachedCamera.inertialBetaOffset !== 0 ||
  83324. this._attachedCamera.inertialRadiusOffset !== 0 ||
  83325. this._attachedCamera.inertialPanningX !== 0 ||
  83326. this._attachedCamera.inertialPanningY !== 0 ||
  83327. this._isPointerDown;
  83328. };
  83329. return AutoRotationBehavior;
  83330. }());
  83331. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  83332. })(BABYLON || (BABYLON = {}));
  83333. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  83334. var BABYLON;
  83335. (function (BABYLON) {
  83336. /**
  83337. * This class can be used to get instrumentation data from a Babylon engine
  83338. */
  83339. var EngineInstrumentation = /** @class */ (function () {
  83340. function EngineInstrumentation(engine) {
  83341. this.engine = engine;
  83342. this._captureGPUFrameTime = false;
  83343. this._gpuFrameTime = new BABYLON.PerfCounter();
  83344. this._captureShaderCompilationTime = false;
  83345. this._shaderCompilationTime = new BABYLON.PerfCounter();
  83346. // Observers
  83347. this._onBeginFrameObserver = null;
  83348. this._onEndFrameObserver = null;
  83349. this._onBeforeShaderCompilationObserver = null;
  83350. this._onAfterShaderCompilationObserver = null;
  83351. }
  83352. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  83353. // Properties
  83354. /**
  83355. * Gets the perf counter used for GPU frame time
  83356. */
  83357. get: function () {
  83358. return this._gpuFrameTime;
  83359. },
  83360. enumerable: true,
  83361. configurable: true
  83362. });
  83363. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  83364. /**
  83365. * Gets the GPU frame time capture status
  83366. */
  83367. get: function () {
  83368. return this._captureGPUFrameTime;
  83369. },
  83370. /**
  83371. * Enable or disable the GPU frame time capture
  83372. */
  83373. set: function (value) {
  83374. var _this = this;
  83375. if (value === this._captureGPUFrameTime) {
  83376. return;
  83377. }
  83378. this._captureGPUFrameTime = value;
  83379. if (value) {
  83380. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  83381. if (!_this._gpuFrameTimeToken) {
  83382. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  83383. }
  83384. });
  83385. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  83386. if (!_this._gpuFrameTimeToken) {
  83387. return;
  83388. }
  83389. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  83390. if (time > -1) {
  83391. _this._gpuFrameTimeToken = null;
  83392. _this._gpuFrameTime.fetchNewFrame();
  83393. _this._gpuFrameTime.addCount(time, true);
  83394. }
  83395. });
  83396. }
  83397. else {
  83398. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83399. this._onBeginFrameObserver = null;
  83400. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83401. this._onEndFrameObserver = null;
  83402. }
  83403. },
  83404. enumerable: true,
  83405. configurable: true
  83406. });
  83407. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  83408. /**
  83409. * Gets the perf counter used for shader compilation time
  83410. */
  83411. get: function () {
  83412. return this._shaderCompilationTime;
  83413. },
  83414. enumerable: true,
  83415. configurable: true
  83416. });
  83417. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  83418. /**
  83419. * Gets the shader compilation time capture status
  83420. */
  83421. get: function () {
  83422. return this._captureShaderCompilationTime;
  83423. },
  83424. /**
  83425. * Enable or disable the shader compilation time capture
  83426. */
  83427. set: function (value) {
  83428. var _this = this;
  83429. if (value === this._captureShaderCompilationTime) {
  83430. return;
  83431. }
  83432. this._captureShaderCompilationTime = value;
  83433. if (value) {
  83434. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  83435. _this._shaderCompilationTime.fetchNewFrame();
  83436. _this._shaderCompilationTime.beginMonitoring();
  83437. });
  83438. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  83439. _this._shaderCompilationTime.endMonitoring();
  83440. });
  83441. }
  83442. else {
  83443. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83444. this._onBeforeShaderCompilationObserver = null;
  83445. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83446. this._onAfterShaderCompilationObserver = null;
  83447. }
  83448. },
  83449. enumerable: true,
  83450. configurable: true
  83451. });
  83452. EngineInstrumentation.prototype.dispose = function () {
  83453. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83454. this._onBeginFrameObserver = null;
  83455. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83456. this._onEndFrameObserver = null;
  83457. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83458. this._onBeforeShaderCompilationObserver = null;
  83459. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83460. this._onAfterShaderCompilationObserver = null;
  83461. this.engine = null;
  83462. };
  83463. return EngineInstrumentation;
  83464. }());
  83465. BABYLON.EngineInstrumentation = EngineInstrumentation;
  83466. })(BABYLON || (BABYLON = {}));
  83467. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  83468. var BABYLON;
  83469. (function (BABYLON) {
  83470. /**
  83471. * This class can be used to get instrumentation data from a Babylon engine
  83472. */
  83473. var SceneInstrumentation = /** @class */ (function () {
  83474. function SceneInstrumentation(scene) {
  83475. var _this = this;
  83476. this.scene = scene;
  83477. this._captureActiveMeshesEvaluationTime = false;
  83478. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  83479. this._captureRenderTargetsRenderTime = false;
  83480. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  83481. this._captureFrameTime = false;
  83482. this._frameTime = new BABYLON.PerfCounter();
  83483. this._captureRenderTime = false;
  83484. this._renderTime = new BABYLON.PerfCounter();
  83485. this._captureInterFrameTime = false;
  83486. this._interFrameTime = new BABYLON.PerfCounter();
  83487. this._captureParticlesRenderTime = false;
  83488. this._particlesRenderTime = new BABYLON.PerfCounter();
  83489. this._captureSpritesRenderTime = false;
  83490. this._spritesRenderTime = new BABYLON.PerfCounter();
  83491. this._capturePhysicsTime = false;
  83492. this._physicsTime = new BABYLON.PerfCounter();
  83493. this._captureAnimationsTime = false;
  83494. this._animationsTime = new BABYLON.PerfCounter();
  83495. // Observers
  83496. this._onBeforeActiveMeshesEvaluationObserver = null;
  83497. this._onAfterActiveMeshesEvaluationObserver = null;
  83498. this._onBeforeRenderTargetsRenderObserver = null;
  83499. this._onAfterRenderTargetsRenderObserver = null;
  83500. this._onAfterRenderObserver = null;
  83501. this._onBeforeDrawPhaseObserver = null;
  83502. this._onAfterDrawPhaseObserver = null;
  83503. this._onBeforeAnimationsObserver = null;
  83504. this._onBeforeParticlesRenderingObserver = null;
  83505. this._onAfterParticlesRenderingObserver = null;
  83506. this._onBeforeSpritesRenderingObserver = null;
  83507. this._onAfterSpritesRenderingObserver = null;
  83508. this._onBeforePhysicsObserver = null;
  83509. this._onAfterPhysicsObserver = null;
  83510. this._onAfterAnimationsObserver = null;
  83511. // Before render
  83512. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  83513. if (_this._captureActiveMeshesEvaluationTime) {
  83514. _this._activeMeshesEvaluationTime.fetchNewFrame();
  83515. }
  83516. if (_this._captureRenderTargetsRenderTime) {
  83517. _this._renderTargetsRenderTime.fetchNewFrame();
  83518. }
  83519. if (_this._captureFrameTime) {
  83520. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  83521. _this._frameTime.beginMonitoring();
  83522. }
  83523. if (_this._captureInterFrameTime) {
  83524. _this._interFrameTime.endMonitoring();
  83525. }
  83526. if (_this._captureParticlesRenderTime) {
  83527. _this._particlesRenderTime.fetchNewFrame();
  83528. }
  83529. if (_this._captureSpritesRenderTime) {
  83530. _this._spritesRenderTime.fetchNewFrame();
  83531. }
  83532. if (_this._captureAnimationsTime) {
  83533. _this._animationsTime.beginMonitoring();
  83534. }
  83535. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  83536. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  83537. });
  83538. // After render
  83539. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  83540. if (_this._captureFrameTime) {
  83541. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  83542. _this._frameTime.endMonitoring();
  83543. }
  83544. if (_this._captureRenderTime) {
  83545. _this._renderTime.endMonitoring(false);
  83546. }
  83547. if (_this._captureInterFrameTime) {
  83548. _this._interFrameTime.beginMonitoring();
  83549. }
  83550. });
  83551. }
  83552. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  83553. // Properties
  83554. /**
  83555. * Gets the perf counter used for active meshes evaluation time
  83556. */
  83557. get: function () {
  83558. return this._activeMeshesEvaluationTime;
  83559. },
  83560. enumerable: true,
  83561. configurable: true
  83562. });
  83563. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  83564. /**
  83565. * Gets the active meshes evaluation time capture status
  83566. */
  83567. get: function () {
  83568. return this._captureActiveMeshesEvaluationTime;
  83569. },
  83570. /**
  83571. * Enable or disable the active meshes evaluation time capture
  83572. */
  83573. set: function (value) {
  83574. var _this = this;
  83575. if (value === this._captureActiveMeshesEvaluationTime) {
  83576. return;
  83577. }
  83578. this._captureActiveMeshesEvaluationTime = value;
  83579. if (value) {
  83580. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  83581. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  83582. _this._activeMeshesEvaluationTime.beginMonitoring();
  83583. });
  83584. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  83585. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  83586. _this._activeMeshesEvaluationTime.endMonitoring();
  83587. });
  83588. }
  83589. else {
  83590. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83591. this._onBeforeActiveMeshesEvaluationObserver = null;
  83592. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83593. this._onAfterActiveMeshesEvaluationObserver = null;
  83594. }
  83595. },
  83596. enumerable: true,
  83597. configurable: true
  83598. });
  83599. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  83600. /**
  83601. * Gets the perf counter used for render targets render time
  83602. */
  83603. get: function () {
  83604. return this._renderTargetsRenderTime;
  83605. },
  83606. enumerable: true,
  83607. configurable: true
  83608. });
  83609. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  83610. /**
  83611. * Gets the render targets render time capture status
  83612. */
  83613. get: function () {
  83614. return this._captureRenderTargetsRenderTime;
  83615. },
  83616. /**
  83617. * Enable or disable the render targets render time capture
  83618. */
  83619. set: function (value) {
  83620. var _this = this;
  83621. if (value === this._captureRenderTargetsRenderTime) {
  83622. return;
  83623. }
  83624. this._captureRenderTargetsRenderTime = value;
  83625. if (value) {
  83626. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  83627. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  83628. _this._renderTargetsRenderTime.beginMonitoring();
  83629. });
  83630. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  83631. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  83632. _this._renderTargetsRenderTime.endMonitoring(false);
  83633. });
  83634. }
  83635. else {
  83636. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83637. this._onBeforeRenderTargetsRenderObserver = null;
  83638. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83639. this._onAfterRenderTargetsRenderObserver = null;
  83640. }
  83641. },
  83642. enumerable: true,
  83643. configurable: true
  83644. });
  83645. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  83646. /**
  83647. * Gets the perf counter used for particles render time
  83648. */
  83649. get: function () {
  83650. return this._particlesRenderTime;
  83651. },
  83652. enumerable: true,
  83653. configurable: true
  83654. });
  83655. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  83656. /**
  83657. * Gets the particles render time capture status
  83658. */
  83659. get: function () {
  83660. return this._captureParticlesRenderTime;
  83661. },
  83662. /**
  83663. * Enable or disable the particles render time capture
  83664. */
  83665. set: function (value) {
  83666. var _this = this;
  83667. if (value === this._captureParticlesRenderTime) {
  83668. return;
  83669. }
  83670. this._captureParticlesRenderTime = value;
  83671. if (value) {
  83672. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  83673. BABYLON.Tools.StartPerformanceCounter("Particles");
  83674. _this._particlesRenderTime.beginMonitoring();
  83675. });
  83676. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  83677. BABYLON.Tools.EndPerformanceCounter("Particles");
  83678. _this._particlesRenderTime.endMonitoring(false);
  83679. });
  83680. }
  83681. else {
  83682. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83683. this._onBeforeParticlesRenderingObserver = null;
  83684. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83685. this._onAfterParticlesRenderingObserver = null;
  83686. }
  83687. },
  83688. enumerable: true,
  83689. configurable: true
  83690. });
  83691. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  83692. /**
  83693. * Gets the perf counter used for sprites render time
  83694. */
  83695. get: function () {
  83696. return this._spritesRenderTime;
  83697. },
  83698. enumerable: true,
  83699. configurable: true
  83700. });
  83701. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  83702. /**
  83703. * Gets the sprites render time capture status
  83704. */
  83705. get: function () {
  83706. return this._captureSpritesRenderTime;
  83707. },
  83708. /**
  83709. * Enable or disable the sprites render time capture
  83710. */
  83711. set: function (value) {
  83712. var _this = this;
  83713. if (value === this._captureSpritesRenderTime) {
  83714. return;
  83715. }
  83716. this._captureSpritesRenderTime = value;
  83717. if (value) {
  83718. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83719. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83720. _this._spritesRenderTime.beginMonitoring();
  83721. });
  83722. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83723. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83724. _this._spritesRenderTime.endMonitoring(false);
  83725. });
  83726. }
  83727. else {
  83728. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83729. this._onBeforeSpritesRenderingObserver = null;
  83730. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83731. this._onAfterSpritesRenderingObserver = null;
  83732. }
  83733. },
  83734. enumerable: true,
  83735. configurable: true
  83736. });
  83737. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83738. /**
  83739. * Gets the perf counter used for physics time
  83740. */
  83741. get: function () {
  83742. return this._physicsTime;
  83743. },
  83744. enumerable: true,
  83745. configurable: true
  83746. });
  83747. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83748. /**
  83749. * Gets the physics time capture status
  83750. */
  83751. get: function () {
  83752. return this._capturePhysicsTime;
  83753. },
  83754. /**
  83755. * Enable or disable the physics time capture
  83756. */
  83757. set: function (value) {
  83758. var _this = this;
  83759. if (value === this._capturePhysicsTime) {
  83760. return;
  83761. }
  83762. this._capturePhysicsTime = value;
  83763. if (value) {
  83764. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83765. BABYLON.Tools.StartPerformanceCounter("Physics");
  83766. _this._physicsTime.beginMonitoring();
  83767. });
  83768. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83769. BABYLON.Tools.EndPerformanceCounter("Physics");
  83770. _this._physicsTime.endMonitoring();
  83771. });
  83772. }
  83773. else {
  83774. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83775. this._onBeforePhysicsObserver = null;
  83776. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83777. this._onAfterPhysicsObserver = null;
  83778. }
  83779. },
  83780. enumerable: true,
  83781. configurable: true
  83782. });
  83783. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83784. /**
  83785. * Gets the perf counter used for animations time
  83786. */
  83787. get: function () {
  83788. return this._animationsTime;
  83789. },
  83790. enumerable: true,
  83791. configurable: true
  83792. });
  83793. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83794. /**
  83795. * Gets the animations time capture status
  83796. */
  83797. get: function () {
  83798. return this._captureAnimationsTime;
  83799. },
  83800. /**
  83801. * Enable or disable the animations time capture
  83802. */
  83803. set: function (value) {
  83804. var _this = this;
  83805. if (value === this._captureAnimationsTime) {
  83806. return;
  83807. }
  83808. this._captureAnimationsTime = value;
  83809. if (value) {
  83810. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83811. _this._animationsTime.endMonitoring();
  83812. });
  83813. }
  83814. else {
  83815. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83816. this._onAfterAnimationsObserver = null;
  83817. }
  83818. },
  83819. enumerable: true,
  83820. configurable: true
  83821. });
  83822. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83823. /**
  83824. * Gets the perf counter used for frame time capture
  83825. */
  83826. get: function () {
  83827. return this._frameTime;
  83828. },
  83829. enumerable: true,
  83830. configurable: true
  83831. });
  83832. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83833. /**
  83834. * Gets the frame time capture status
  83835. */
  83836. get: function () {
  83837. return this._captureFrameTime;
  83838. },
  83839. /**
  83840. * Enable or disable the frame time capture
  83841. */
  83842. set: function (value) {
  83843. this._captureFrameTime = value;
  83844. },
  83845. enumerable: true,
  83846. configurable: true
  83847. });
  83848. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83849. /**
  83850. * Gets the perf counter used for inter-frames time capture
  83851. */
  83852. get: function () {
  83853. return this._interFrameTime;
  83854. },
  83855. enumerable: true,
  83856. configurable: true
  83857. });
  83858. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  83859. /**
  83860. * Gets the inter-frames time capture status
  83861. */
  83862. get: function () {
  83863. return this._captureInterFrameTime;
  83864. },
  83865. /**
  83866. * Enable or disable the inter-frames time capture
  83867. */
  83868. set: function (value) {
  83869. this._captureInterFrameTime = value;
  83870. },
  83871. enumerable: true,
  83872. configurable: true
  83873. });
  83874. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  83875. /**
  83876. * Gets the perf counter used for render time capture
  83877. */
  83878. get: function () {
  83879. return this._renderTime;
  83880. },
  83881. enumerable: true,
  83882. configurable: true
  83883. });
  83884. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  83885. /**
  83886. * Gets the render time capture status
  83887. */
  83888. get: function () {
  83889. return this._captureRenderTime;
  83890. },
  83891. /**
  83892. * Enable or disable the render time capture
  83893. */
  83894. set: function (value) {
  83895. var _this = this;
  83896. if (value === this._captureRenderTime) {
  83897. return;
  83898. }
  83899. this._captureRenderTime = value;
  83900. if (value) {
  83901. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  83902. _this._renderTime.beginMonitoring();
  83903. BABYLON.Tools.StartPerformanceCounter("Main render");
  83904. });
  83905. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  83906. _this._renderTime.endMonitoring(false);
  83907. BABYLON.Tools.EndPerformanceCounter("Main render");
  83908. });
  83909. }
  83910. else {
  83911. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83912. this._onBeforeDrawPhaseObserver = null;
  83913. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83914. this._onAfterDrawPhaseObserver = null;
  83915. }
  83916. },
  83917. enumerable: true,
  83918. configurable: true
  83919. });
  83920. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  83921. /**
  83922. * Gets the perf counter used for draw calls
  83923. */
  83924. get: function () {
  83925. return this.scene.getEngine()._drawCalls;
  83926. },
  83927. enumerable: true,
  83928. configurable: true
  83929. });
  83930. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  83931. /**
  83932. * Gets the perf counter used for texture collisions
  83933. */
  83934. get: function () {
  83935. return this.scene.getEngine()._textureCollisions;
  83936. },
  83937. enumerable: true,
  83938. configurable: true
  83939. });
  83940. SceneInstrumentation.prototype.dispose = function () {
  83941. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83942. this._onAfterRenderObserver = null;
  83943. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83944. this._onBeforeActiveMeshesEvaluationObserver = null;
  83945. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83946. this._onAfterActiveMeshesEvaluationObserver = null;
  83947. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83948. this._onBeforeRenderTargetsRenderObserver = null;
  83949. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83950. this._onAfterRenderTargetsRenderObserver = null;
  83951. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83952. this._onBeforeAnimationsObserver = null;
  83953. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83954. this._onBeforeParticlesRenderingObserver = null;
  83955. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83956. this._onAfterParticlesRenderingObserver = null;
  83957. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83958. this._onBeforeSpritesRenderingObserver = null;
  83959. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83960. this._onAfterSpritesRenderingObserver = null;
  83961. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83962. this._onBeforeDrawPhaseObserver = null;
  83963. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83964. this._onAfterDrawPhaseObserver = null;
  83965. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83966. this._onBeforePhysicsObserver = null;
  83967. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83968. this._onAfterPhysicsObserver = null;
  83969. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83970. this._onAfterAnimationsObserver = null;
  83971. this.scene = null;
  83972. };
  83973. return SceneInstrumentation;
  83974. }());
  83975. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83976. })(BABYLON || (BABYLON = {}));
  83977. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83978. var BABYLON;
  83979. (function (BABYLON) {
  83980. var _TimeToken = /** @class */ (function () {
  83981. function _TimeToken() {
  83982. this._timeElapsedQueryEnded = false;
  83983. }
  83984. return _TimeToken;
  83985. }());
  83986. BABYLON._TimeToken = _TimeToken;
  83987. })(BABYLON || (BABYLON = {}));
  83988. //# sourceMappingURL=babylon.timeToken.js.map
  83989. var BABYLON;
  83990. (function (BABYLON) {
  83991. /**
  83992. * Background material defines definition.
  83993. * @ignore Mainly internal Use
  83994. */
  83995. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83996. __extends(BackgroundMaterialDefines, _super);
  83997. /**
  83998. * Constructor of the defines.
  83999. */
  84000. function BackgroundMaterialDefines() {
  84001. var _this = _super.call(this) || this;
  84002. /**
  84003. * True if the diffuse texture is in use.
  84004. */
  84005. _this.DIFFUSE = false;
  84006. /**
  84007. * The direct UV channel to use.
  84008. */
  84009. _this.DIFFUSEDIRECTUV = 0;
  84010. /**
  84011. * True if the diffuse texture is in gamma space.
  84012. */
  84013. _this.GAMMADIFFUSE = false;
  84014. /**
  84015. * True if the diffuse texture has opacity in the alpha channel.
  84016. */
  84017. _this.DIFFUSEHASALPHA = false;
  84018. /**
  84019. * True if you want the material to fade to transparent at grazing angle.
  84020. */
  84021. _this.OPACITYFRESNEL = false;
  84022. /**
  84023. * True if an extra blur needs to be added in the reflection.
  84024. */
  84025. _this.REFLECTIONBLUR = false;
  84026. /**
  84027. * True if you want the material to fade to reflection at grazing angle.
  84028. */
  84029. _this.REFLECTIONFRESNEL = false;
  84030. /**
  84031. * True if you want the material to falloff as far as you move away from the scene center.
  84032. */
  84033. _this.REFLECTIONFALLOFF = false;
  84034. /**
  84035. * False if the current Webgl implementation does not support the texture lod extension.
  84036. */
  84037. _this.TEXTURELODSUPPORT = false;
  84038. /**
  84039. * True to ensure the data are premultiplied.
  84040. */
  84041. _this.PREMULTIPLYALPHA = false;
  84042. /**
  84043. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  84044. */
  84045. _this.USERGBCOLOR = false;
  84046. /**
  84047. * True to add noise in order to reduce the banding effect.
  84048. */
  84049. _this.NOISE = false;
  84050. // Image Processing Configuration.
  84051. _this.IMAGEPROCESSING = false;
  84052. _this.VIGNETTE = false;
  84053. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84054. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84055. _this.TONEMAPPING = false;
  84056. _this.CONTRAST = false;
  84057. _this.COLORCURVES = false;
  84058. _this.COLORGRADING = false;
  84059. _this.COLORGRADING3D = false;
  84060. _this.SAMPLER3DGREENDEPTH = false;
  84061. _this.SAMPLER3DBGRMAP = false;
  84062. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84063. _this.EXPOSURE = false;
  84064. // Reflection.
  84065. _this.REFLECTION = false;
  84066. _this.REFLECTIONMAP_3D = false;
  84067. _this.REFLECTIONMAP_SPHERICAL = false;
  84068. _this.REFLECTIONMAP_PLANAR = false;
  84069. _this.REFLECTIONMAP_CUBIC = false;
  84070. _this.REFLECTIONMAP_PROJECTION = false;
  84071. _this.REFLECTIONMAP_SKYBOX = false;
  84072. _this.REFLECTIONMAP_EXPLICIT = false;
  84073. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84074. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84075. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84076. _this.INVERTCUBICMAP = false;
  84077. _this.REFLECTIONMAP_OPPOSITEZ = false;
  84078. _this.LODINREFLECTIONALPHA = false;
  84079. _this.GAMMAREFLECTION = false;
  84080. // Default BJS.
  84081. _this.MAINUV1 = false;
  84082. _this.MAINUV2 = false;
  84083. _this.UV1 = false;
  84084. _this.UV2 = false;
  84085. _this.CLIPPLANE = false;
  84086. _this.POINTSIZE = false;
  84087. _this.FOG = false;
  84088. _this.NORMAL = false;
  84089. _this.NUM_BONE_INFLUENCERS = 0;
  84090. _this.BonesPerMesh = 0;
  84091. _this.INSTANCES = false;
  84092. _this.SHADOWFLOAT = false;
  84093. _this.rebuild();
  84094. return _this;
  84095. }
  84096. return BackgroundMaterialDefines;
  84097. }(BABYLON.MaterialDefines));
  84098. /**
  84099. * Background material used to create an efficient environement around your scene.
  84100. */
  84101. var BackgroundMaterial = /** @class */ (function (_super) {
  84102. __extends(BackgroundMaterial, _super);
  84103. /**
  84104. * Instantiates a Background Material in the given scene
  84105. * @param name The friendly name of the material
  84106. * @param scene The scene to add the material to
  84107. */
  84108. function BackgroundMaterial(name, scene) {
  84109. var _this = _super.call(this, name, scene) || this;
  84110. /**
  84111. * Key light Color (multiply against the R channel of the environement texture)
  84112. */
  84113. _this.primaryColor = BABYLON.Color3.White();
  84114. /**
  84115. * Key light Level (allowing HDR output of the background)
  84116. */
  84117. _this.primaryLevel = 1;
  84118. /**
  84119. * Secondary light Color (multiply against the G channel of the environement texture)
  84120. */
  84121. _this.secondaryColor = BABYLON.Color3.Gray();
  84122. /**
  84123. * Secondary light Level (allowing HDR output of the background)
  84124. */
  84125. _this.secondaryLevel = 1;
  84126. /**
  84127. * Tertiary light Color (multiply against the B channel of the environement texture)
  84128. */
  84129. _this.tertiaryColor = BABYLON.Color3.Black();
  84130. /**
  84131. * Tertiary light Level (allowing HDR output of the background)
  84132. */
  84133. _this.tertiaryLevel = 1;
  84134. /**
  84135. * Reflection Texture used in the material.
  84136. * Should be author in a specific way for the best result (refer to the documentation).
  84137. */
  84138. _this.reflectionTexture = null;
  84139. /**
  84140. * Reflection Texture level of blur.
  84141. *
  84142. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  84143. * texture twice.
  84144. */
  84145. _this.reflectionBlur = 0;
  84146. /**
  84147. * Diffuse Texture used in the material.
  84148. * Should be author in a specific way for the best result (refer to the documentation).
  84149. */
  84150. _this.diffuseTexture = null;
  84151. _this._shadowLights = null;
  84152. /**
  84153. * Specify the list of lights casting shadow on the material.
  84154. * All scene shadow lights will be included if null.
  84155. */
  84156. _this.shadowLights = null;
  84157. /**
  84158. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  84159. * soft lighting on the background.
  84160. */
  84161. _this.shadowBlurScale = 1;
  84162. /**
  84163. * Helps adjusting the shadow to a softer level if required.
  84164. * 0 means black shadows and 1 means no shadows.
  84165. */
  84166. _this.shadowLevel = 0;
  84167. /**
  84168. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  84169. * It is usually zero but might be interesting to modify according to your setup.
  84170. */
  84171. _this.sceneCenter = BABYLON.Vector3.Zero();
  84172. /**
  84173. * This helps specifying that the material is falling off to the sky box at grazing angle.
  84174. * This helps ensuring a nice transition when the camera goes under the ground.
  84175. */
  84176. _this.opacityFresnel = true;
  84177. /**
  84178. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  84179. * This helps adding a mirror texture on the ground.
  84180. */
  84181. _this.reflectionFresnel = false;
  84182. /**
  84183. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  84184. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  84185. */
  84186. _this.reflectionFalloffDistance = 0.0;
  84187. /**
  84188. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  84189. */
  84190. _this.reflectionAmount = 1.0;
  84191. /**
  84192. * This specifies the weight of the reflection at grazing angle.
  84193. */
  84194. _this.reflectionReflectance0 = 0.05;
  84195. /**
  84196. * This specifies the weight of the reflection at a perpendicular point of view.
  84197. */
  84198. _this.reflectionReflectance90 = 0.5;
  84199. /**
  84200. * Helps to directly use the maps channels instead of their level.
  84201. */
  84202. _this.useRGBColor = true;
  84203. /**
  84204. * This helps reducing the banding effect that could occur on the background.
  84205. */
  84206. _this.enableNoise = false;
  84207. _this._maxSimultaneousLights = 4;
  84208. /**
  84209. * Number of Simultaneous lights allowed on the material.
  84210. */
  84211. _this.maxSimultaneousLights = 4;
  84212. /**
  84213. * Keep track of the image processing observer to allow dispose and replace.
  84214. */
  84215. _this._imageProcessingObserver = null;
  84216. // Temp values kept as cache in the material.
  84217. _this._renderTargets = new BABYLON.SmartArray(16);
  84218. _this._reflectionControls = BABYLON.Vector4.Zero();
  84219. // Setup the default processing configuration to the scene.
  84220. _this._attachImageProcessingConfiguration(null);
  84221. _this.getRenderTargetTextures = function () {
  84222. _this._renderTargets.reset();
  84223. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  84224. _this._renderTargets.push(_this._diffuseTexture);
  84225. }
  84226. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  84227. _this._renderTargets.push(_this._reflectionTexture);
  84228. }
  84229. return _this._renderTargets;
  84230. };
  84231. return _this;
  84232. }
  84233. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  84234. /**
  84235. * Sets the reflection reflectance fresnel values according to the default standard
  84236. * empirically know to work well :-)
  84237. */
  84238. set: function (value) {
  84239. var reflectionWeight = value;
  84240. if (reflectionWeight < 0.5) {
  84241. reflectionWeight = reflectionWeight * 2.0;
  84242. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  84243. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  84244. }
  84245. else {
  84246. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  84247. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  84248. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  84249. }
  84250. },
  84251. enumerable: true,
  84252. configurable: true
  84253. });
  84254. /**
  84255. * Attaches a new image processing configuration to the PBR Material.
  84256. * @param configuration (if null the scene configuration will be use)
  84257. */
  84258. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  84259. var _this = this;
  84260. if (configuration === this._imageProcessingConfiguration) {
  84261. return;
  84262. }
  84263. // Detaches observer.
  84264. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84265. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84266. }
  84267. // Pick the scene configuration if needed.
  84268. if (!configuration) {
  84269. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  84270. }
  84271. else {
  84272. this._imageProcessingConfiguration = configuration;
  84273. }
  84274. // Attaches observer.
  84275. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84276. _this._markAllSubMeshesAsImageProcessingDirty();
  84277. });
  84278. };
  84279. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  84280. /**
  84281. * Gets the image processing configuration used either in this material.
  84282. */
  84283. get: function () {
  84284. return this._imageProcessingConfiguration;
  84285. },
  84286. /**
  84287. * Sets the Default image processing configuration used either in the this material.
  84288. *
  84289. * If sets to null, the scene one is in use.
  84290. */
  84291. set: function (value) {
  84292. this._attachImageProcessingConfiguration(value);
  84293. // Ensure the effect will be rebuilt.
  84294. this._markAllSubMeshesAsTexturesDirty();
  84295. },
  84296. enumerable: true,
  84297. configurable: true
  84298. });
  84299. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  84300. /**
  84301. * Gets wether the color curves effect is enabled.
  84302. */
  84303. get: function () {
  84304. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84305. },
  84306. /**
  84307. * Sets wether the color curves effect is enabled.
  84308. */
  84309. set: function (value) {
  84310. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84311. },
  84312. enumerable: true,
  84313. configurable: true
  84314. });
  84315. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  84316. /**
  84317. * Gets wether the color grading effect is enabled.
  84318. */
  84319. get: function () {
  84320. return this.imageProcessingConfiguration.colorGradingEnabled;
  84321. },
  84322. /**
  84323. * Gets wether the color grading effect is enabled.
  84324. */
  84325. set: function (value) {
  84326. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84327. },
  84328. enumerable: true,
  84329. configurable: true
  84330. });
  84331. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  84332. /**
  84333. * Gets wether tonemapping is enabled or not.
  84334. */
  84335. get: function () {
  84336. return this._imageProcessingConfiguration.toneMappingEnabled;
  84337. },
  84338. /**
  84339. * Sets wether tonemapping is enabled or not
  84340. */
  84341. set: function (value) {
  84342. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84343. },
  84344. enumerable: true,
  84345. configurable: true
  84346. });
  84347. ;
  84348. ;
  84349. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  84350. /**
  84351. * The camera exposure used on this material.
  84352. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84353. * This corresponds to a photographic exposure.
  84354. */
  84355. get: function () {
  84356. return this._imageProcessingConfiguration.exposure;
  84357. },
  84358. /**
  84359. * The camera exposure used on this material.
  84360. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84361. * This corresponds to a photographic exposure.
  84362. */
  84363. set: function (value) {
  84364. this._imageProcessingConfiguration.exposure = value;
  84365. },
  84366. enumerable: true,
  84367. configurable: true
  84368. });
  84369. ;
  84370. ;
  84371. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  84372. /**
  84373. * Gets The camera contrast used on this material.
  84374. */
  84375. get: function () {
  84376. return this._imageProcessingConfiguration.contrast;
  84377. },
  84378. /**
  84379. * Sets The camera contrast used on this material.
  84380. */
  84381. set: function (value) {
  84382. this._imageProcessingConfiguration.contrast = value;
  84383. },
  84384. enumerable: true,
  84385. configurable: true
  84386. });
  84387. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  84388. /**
  84389. * Gets the Color Grading 2D Lookup Texture.
  84390. */
  84391. get: function () {
  84392. return this._imageProcessingConfiguration.colorGradingTexture;
  84393. },
  84394. /**
  84395. * Sets the Color Grading 2D Lookup Texture.
  84396. */
  84397. set: function (value) {
  84398. this.imageProcessingConfiguration.colorGradingTexture = value;
  84399. },
  84400. enumerable: true,
  84401. configurable: true
  84402. });
  84403. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  84404. /**
  84405. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84406. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84407. * 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;
  84408. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84409. */
  84410. get: function () {
  84411. return this.imageProcessingConfiguration.colorCurves;
  84412. },
  84413. /**
  84414. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84415. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84416. * 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;
  84417. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84418. */
  84419. set: function (value) {
  84420. this.imageProcessingConfiguration.colorCurves = value;
  84421. },
  84422. enumerable: true,
  84423. configurable: true
  84424. });
  84425. /**
  84426. * The entire material has been created in order to prevent overdraw.
  84427. * @returns false
  84428. */
  84429. BackgroundMaterial.prototype.needAlphaTesting = function () {
  84430. return true;
  84431. };
  84432. /**
  84433. * The entire material has been created in order to prevent overdraw.
  84434. * @returns true if blending is enable
  84435. */
  84436. BackgroundMaterial.prototype.needAlphaBlending = function () {
  84437. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  84438. };
  84439. /**
  84440. * Checks wether the material is ready to be rendered for a given mesh.
  84441. * @param mesh The mesh to render
  84442. * @param subMesh The submesh to check against
  84443. * @param useInstances Specify wether or not the material is used with instances
  84444. * @returns true if all the dependencies are ready (Textures, Effects...)
  84445. */
  84446. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  84447. var _this = this;
  84448. if (useInstances === void 0) { useInstances = false; }
  84449. if (subMesh.effect && this.isFrozen) {
  84450. if (this._wasPreviouslyReady) {
  84451. return true;
  84452. }
  84453. }
  84454. if (!subMesh._materialDefines) {
  84455. subMesh._materialDefines = new BackgroundMaterialDefines();
  84456. }
  84457. var scene = this.getScene();
  84458. var defines = subMesh._materialDefines;
  84459. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84460. if (defines._renderId === scene.getRenderId()) {
  84461. return true;
  84462. }
  84463. }
  84464. var engine = scene.getEngine();
  84465. // Lights
  84466. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  84467. defines._needNormals = true;
  84468. // Textures
  84469. if (defines._areTexturesDirty) {
  84470. defines._needUVs = false;
  84471. if (scene.texturesEnabled) {
  84472. if (scene.getEngine().getCaps().textureLOD) {
  84473. defines.TEXTURELODSUPPORT = true;
  84474. }
  84475. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84476. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  84477. return false;
  84478. }
  84479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  84480. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  84481. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  84482. defines.OPACITYFRESNEL = this._opacityFresnel;
  84483. }
  84484. else {
  84485. defines.DIFFUSE = false;
  84486. defines.DIFFUSEHASALPHA = false;
  84487. defines.GAMMADIFFUSE = false;
  84488. defines.OPACITYFRESNEL = false;
  84489. }
  84490. var reflectionTexture = this._reflectionTexture;
  84491. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84492. if (!reflectionTexture.isReadyOrNotBlocking()) {
  84493. return false;
  84494. }
  84495. defines.REFLECTION = true;
  84496. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  84497. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  84498. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  84499. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  84500. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  84501. defines.INVERTCUBICMAP = true;
  84502. }
  84503. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  84504. switch (reflectionTexture.coordinatesMode) {
  84505. case BABYLON.Texture.CUBIC_MODE:
  84506. case BABYLON.Texture.INVCUBIC_MODE:
  84507. defines.REFLECTIONMAP_CUBIC = true;
  84508. break;
  84509. case BABYLON.Texture.EXPLICIT_MODE:
  84510. defines.REFLECTIONMAP_EXPLICIT = true;
  84511. break;
  84512. case BABYLON.Texture.PLANAR_MODE:
  84513. defines.REFLECTIONMAP_PLANAR = true;
  84514. break;
  84515. case BABYLON.Texture.PROJECTION_MODE:
  84516. defines.REFLECTIONMAP_PROJECTION = true;
  84517. break;
  84518. case BABYLON.Texture.SKYBOX_MODE:
  84519. defines.REFLECTIONMAP_SKYBOX = true;
  84520. break;
  84521. case BABYLON.Texture.SPHERICAL_MODE:
  84522. defines.REFLECTIONMAP_SPHERICAL = true;
  84523. break;
  84524. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  84525. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  84526. break;
  84527. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  84528. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  84529. break;
  84530. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  84531. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  84532. break;
  84533. }
  84534. if (this.reflectionFresnel) {
  84535. defines.REFLECTIONFRESNEL = true;
  84536. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  84537. this._reflectionControls.x = this.reflectionAmount;
  84538. this._reflectionControls.y = this.reflectionReflectance0;
  84539. this._reflectionControls.z = this.reflectionReflectance90;
  84540. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  84541. }
  84542. else {
  84543. defines.REFLECTIONFRESNEL = false;
  84544. defines.REFLECTIONFALLOFF = false;
  84545. }
  84546. }
  84547. else {
  84548. defines.REFLECTION = false;
  84549. defines.REFLECTIONFALLOFF = false;
  84550. defines.REFLECTIONBLUR = false;
  84551. defines.REFLECTIONMAP_3D = false;
  84552. defines.REFLECTIONMAP_SPHERICAL = false;
  84553. defines.REFLECTIONMAP_PLANAR = false;
  84554. defines.REFLECTIONMAP_CUBIC = false;
  84555. defines.REFLECTIONMAP_PROJECTION = false;
  84556. defines.REFLECTIONMAP_SKYBOX = false;
  84557. defines.REFLECTIONMAP_EXPLICIT = false;
  84558. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84559. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84560. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84561. defines.INVERTCUBICMAP = false;
  84562. defines.REFLECTIONMAP_OPPOSITEZ = false;
  84563. defines.LODINREFLECTIONALPHA = false;
  84564. defines.GAMMAREFLECTION = false;
  84565. }
  84566. }
  84567. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  84568. defines.USERGBCOLOR = this._useRGBColor;
  84569. defines.NOISE = this._enableNoise;
  84570. }
  84571. if (defines._areImageProcessingDirty) {
  84572. if (!this._imageProcessingConfiguration.isReady()) {
  84573. return false;
  84574. }
  84575. this._imageProcessingConfiguration.prepareDefines(defines);
  84576. }
  84577. // Misc.
  84578. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  84579. // Values that need to be evaluated on every frame
  84580. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  84581. // Attribs
  84582. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  84583. if (mesh) {
  84584. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84585. mesh.createNormals(true);
  84586. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  84587. }
  84588. }
  84589. }
  84590. // Get correct effect
  84591. if (defines.isDirty) {
  84592. defines.markAsProcessed();
  84593. scene.resetCachedMaterial();
  84594. // Fallbacks
  84595. var fallbacks = new BABYLON.EffectFallbacks();
  84596. if (defines.FOG) {
  84597. fallbacks.addFallback(0, "FOG");
  84598. }
  84599. if (defines.POINTSIZE) {
  84600. fallbacks.addFallback(1, "POINTSIZE");
  84601. }
  84602. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  84603. if (defines.NUM_BONE_INFLUENCERS > 0) {
  84604. fallbacks.addCPUSkinningFallback(0, mesh);
  84605. }
  84606. //Attributes
  84607. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84608. if (defines.NORMAL) {
  84609. attribs.push(BABYLON.VertexBuffer.NormalKind);
  84610. }
  84611. if (defines.UV1) {
  84612. attribs.push(BABYLON.VertexBuffer.UVKind);
  84613. }
  84614. if (defines.UV2) {
  84615. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84616. }
  84617. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  84618. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  84619. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  84620. "vFogInfos", "vFogColor", "pointSize",
  84621. "vClipPlane", "mBones",
  84622. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  84623. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  84624. "shadowLevel", "alpha",
  84625. "vBackgroundCenter", "vReflectionControl",
  84626. "vDiffuseInfos", "diffuseMatrix",
  84627. ];
  84628. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  84629. var uniformBuffers = ["Material", "Scene"];
  84630. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  84631. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  84632. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  84633. uniformsNames: uniforms,
  84634. uniformBuffersNames: uniformBuffers,
  84635. samplers: samplers,
  84636. defines: defines,
  84637. maxSimultaneousLights: this._maxSimultaneousLights
  84638. });
  84639. var onCompiled = function (effect) {
  84640. if (_this.onCompiled) {
  84641. _this.onCompiled(effect);
  84642. }
  84643. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  84644. };
  84645. var join = defines.toString();
  84646. subMesh.setEffect(scene.getEngine().createEffect("background", {
  84647. attributes: attribs,
  84648. uniformsNames: uniforms,
  84649. uniformBuffersNames: uniformBuffers,
  84650. samplers: samplers,
  84651. defines: join,
  84652. fallbacks: fallbacks,
  84653. onCompiled: onCompiled,
  84654. onError: this.onError,
  84655. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  84656. }, engine), defines);
  84657. this.buildUniformLayout();
  84658. }
  84659. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84660. return false;
  84661. }
  84662. defines._renderId = scene.getRenderId();
  84663. this._wasPreviouslyReady = true;
  84664. return true;
  84665. };
  84666. /**
  84667. * Build the uniform buffer used in the material.
  84668. */
  84669. BackgroundMaterial.prototype.buildUniformLayout = function () {
  84670. // Order is important !
  84671. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  84672. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  84673. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  84674. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  84675. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  84676. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  84677. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  84678. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  84679. this._uniformBuffer.addUniform("pointSize", 1);
  84680. this._uniformBuffer.addUniform("shadowLevel", 1);
  84681. this._uniformBuffer.addUniform("alpha", 1);
  84682. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  84683. this._uniformBuffer.addUniform("vReflectionControl", 4);
  84684. this._uniformBuffer.create();
  84685. };
  84686. /**
  84687. * Unbind the material.
  84688. */
  84689. BackgroundMaterial.prototype.unbind = function () {
  84690. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  84691. this._uniformBuffer.setTexture("diffuseSampler", null);
  84692. }
  84693. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  84694. this._uniformBuffer.setTexture("reflectionSampler", null);
  84695. }
  84696. _super.prototype.unbind.call(this);
  84697. };
  84698. /**
  84699. * Bind only the world matrix to the material.
  84700. * @param world The world matrix to bind.
  84701. */
  84702. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  84703. this._activeEffect.setMatrix("world", world);
  84704. };
  84705. /**
  84706. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  84707. * @param world The world matrix to bind.
  84708. * @param subMesh The submesh to bind for.
  84709. */
  84710. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84711. var scene = this.getScene();
  84712. var defines = subMesh._materialDefines;
  84713. if (!defines) {
  84714. return;
  84715. }
  84716. var effect = subMesh.effect;
  84717. if (!effect) {
  84718. return;
  84719. }
  84720. this._activeEffect = effect;
  84721. // Matrices
  84722. this.bindOnlyWorldMatrix(world);
  84723. // Bones
  84724. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  84725. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  84726. if (mustRebind) {
  84727. this._uniformBuffer.bindToEffect(effect, "Material");
  84728. this.bindViewProjection(effect);
  84729. var reflectionTexture = this._reflectionTexture;
  84730. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  84731. // Texture uniforms
  84732. if (scene.texturesEnabled) {
  84733. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84734. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  84735. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  84736. }
  84737. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84738. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  84739. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  84740. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  84741. }
  84742. }
  84743. if (this.shadowLevel > 0) {
  84744. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  84745. }
  84746. this._uniformBuffer.updateFloat("alpha", this.alpha);
  84747. // Point size
  84748. if (this.pointsCloud) {
  84749. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  84750. }
  84751. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  84752. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  84753. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  84754. }
  84755. // Textures
  84756. if (scene.texturesEnabled) {
  84757. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84758. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  84759. }
  84760. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84761. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  84762. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84763. }
  84764. else if (!defines.REFLECTIONBLUR) {
  84765. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84766. }
  84767. else {
  84768. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  84769. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  84770. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  84771. }
  84772. if (defines.REFLECTIONFRESNEL) {
  84773. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  84774. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  84775. }
  84776. }
  84777. }
  84778. // Clip plane
  84779. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84780. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84781. }
  84782. if (mustRebind || !this.isFrozen) {
  84783. if (scene.lightsEnabled) {
  84784. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84785. }
  84786. // View
  84787. this.bindView(effect);
  84788. // Fog
  84789. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84790. // image processing
  84791. this._imageProcessingConfiguration.bind(this._activeEffect);
  84792. }
  84793. this._uniformBuffer.update();
  84794. this._afterBind(mesh);
  84795. };
  84796. /**
  84797. * Dispose the material.
  84798. * @param forceDisposeEffect Force disposal of the associated effect.
  84799. * @param forceDisposeTextures Force disposal of the associated textures.
  84800. */
  84801. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84802. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84803. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84804. if (forceDisposeTextures) {
  84805. if (this.diffuseTexture) {
  84806. this.diffuseTexture.dispose();
  84807. }
  84808. if (this.reflectionTexture) {
  84809. this.reflectionTexture.dispose();
  84810. }
  84811. }
  84812. this._renderTargets.dispose();
  84813. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84814. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84815. }
  84816. _super.prototype.dispose.call(this, forceDisposeEffect);
  84817. };
  84818. /**
  84819. * Clones the material.
  84820. * @param name The cloned name.
  84821. * @returns The cloned material.
  84822. */
  84823. BackgroundMaterial.prototype.clone = function (name) {
  84824. var _this = this;
  84825. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84826. };
  84827. /**
  84828. * Serializes the current material to its JSON representation.
  84829. * @returns The JSON representation.
  84830. */
  84831. BackgroundMaterial.prototype.serialize = function () {
  84832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84833. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84834. return serializationObject;
  84835. };
  84836. /**
  84837. * Gets the class name of the material
  84838. * @returns "BackgroundMaterial"
  84839. */
  84840. BackgroundMaterial.prototype.getClassName = function () {
  84841. return "BackgroundMaterial";
  84842. };
  84843. /**
  84844. * Parse a JSON input to create back a background material.
  84845. * @param source The JSON data to parse
  84846. * @param scene The scene to create the parsed material in
  84847. * @param rootUrl The root url of the assets the material depends upon
  84848. * @returns the instantiated BackgroundMaterial.
  84849. */
  84850. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  84851. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  84852. };
  84853. /**
  84854. * Standard reflectance value at parallel view angle.
  84855. */
  84856. BackgroundMaterial.StandardReflectance0 = 0.05;
  84857. /**
  84858. * Standard reflectance value at grazing angle.
  84859. */
  84860. BackgroundMaterial.StandardReflectance90 = 0.5;
  84861. __decorate([
  84862. BABYLON.serializeAsColor3()
  84863. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  84864. __decorate([
  84865. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84866. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  84867. __decorate([
  84868. BABYLON.serialize()
  84869. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  84870. __decorate([
  84871. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84872. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  84873. __decorate([
  84874. BABYLON.serializeAsColor3()
  84875. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  84876. __decorate([
  84877. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84878. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  84879. __decorate([
  84880. BABYLON.serialize()
  84881. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  84882. __decorate([
  84883. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84884. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  84885. __decorate([
  84886. BABYLON.serializeAsColor3()
  84887. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  84888. __decorate([
  84889. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84890. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  84891. __decorate([
  84892. BABYLON.serialize()
  84893. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  84894. __decorate([
  84895. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84896. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  84897. __decorate([
  84898. BABYLON.serializeAsTexture()
  84899. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  84900. __decorate([
  84901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84902. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  84903. __decorate([
  84904. BABYLON.serialize()
  84905. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  84906. __decorate([
  84907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84908. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  84909. __decorate([
  84910. BABYLON.serializeAsTexture()
  84911. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  84912. __decorate([
  84913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84914. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  84915. __decorate([
  84916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84917. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  84918. __decorate([
  84919. BABYLON.serialize()
  84920. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  84921. __decorate([
  84922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84923. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  84924. __decorate([
  84925. BABYLON.serialize()
  84926. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  84927. __decorate([
  84928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84929. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  84930. __decorate([
  84931. BABYLON.serializeAsVector3()
  84932. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  84933. __decorate([
  84934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84935. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  84936. __decorate([
  84937. BABYLON.serialize()
  84938. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  84939. __decorate([
  84940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84941. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  84942. __decorate([
  84943. BABYLON.serialize()
  84944. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  84945. __decorate([
  84946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84947. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  84948. __decorate([
  84949. BABYLON.serialize()
  84950. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  84951. __decorate([
  84952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84953. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  84954. __decorate([
  84955. BABYLON.serialize()
  84956. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  84957. __decorate([
  84958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84959. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  84960. __decorate([
  84961. BABYLON.serialize()
  84962. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  84963. __decorate([
  84964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84965. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  84966. __decorate([
  84967. BABYLON.serialize()
  84968. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  84969. __decorate([
  84970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84971. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  84972. __decorate([
  84973. BABYLON.serialize()
  84974. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  84975. __decorate([
  84976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84977. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  84978. __decorate([
  84979. BABYLON.serialize()
  84980. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  84981. __decorate([
  84982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84983. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  84984. __decorate([
  84985. BABYLON.serialize()
  84986. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  84987. __decorate([
  84988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84989. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  84990. __decorate([
  84991. BABYLON.serializeAsImageProcessingConfiguration()
  84992. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  84993. return BackgroundMaterial;
  84994. }(BABYLON.PushMaterial));
  84995. BABYLON.BackgroundMaterial = BackgroundMaterial;
  84996. })(BABYLON || (BABYLON = {}));
  84997. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  84998. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84999. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85000. s = arguments[i];
  85001. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85002. t[p] = s[p];
  85003. }
  85004. return t;
  85005. };
  85006. var BABYLON;
  85007. (function (BABYLON) {
  85008. /**
  85009. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  85010. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  85011. * It also helps with the default setup of your imageProcessing configuration.
  85012. */
  85013. var EnvironmentHelper = /** @class */ (function () {
  85014. /**
  85015. * constructor
  85016. * @param options
  85017. * @param scene The scene to add the material to
  85018. */
  85019. function EnvironmentHelper(options, scene) {
  85020. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  85021. this._scene = scene;
  85022. this._setupBackground();
  85023. this._setupImageProcessing();
  85024. }
  85025. /**
  85026. * Creates the default options for the helper.
  85027. */
  85028. EnvironmentHelper._getDefaultOptions = function () {
  85029. return {
  85030. createGround: true,
  85031. groundSize: 15,
  85032. groundTexture: this._groundTextureCDNUrl,
  85033. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85034. groundOpacity: 0.9,
  85035. enableGroundShadow: true,
  85036. groundShadowLevel: 0.5,
  85037. enableGroundMirror: false,
  85038. groundMirrorSizeRatio: 0.3,
  85039. groundMirrorBlurKernel: 64,
  85040. groundMirrorAmount: 1,
  85041. groundMirrorFresnelWeight: 1,
  85042. groundMirrorFallOffDistance: 0,
  85043. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  85044. groundYBias: 0.00001,
  85045. createSkybox: true,
  85046. skyboxSize: 20,
  85047. skyboxTexture: this._skyboxTextureCDNUrl,
  85048. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85049. backgroundYRotation: 0,
  85050. sizeAuto: true,
  85051. rootPosition: BABYLON.Vector3.Zero(),
  85052. setupImageProcessing: true,
  85053. environmentTexture: this._environmentTextureCDNUrl,
  85054. cameraExposure: 0.8,
  85055. cameraContrast: 1.2,
  85056. toneMappingEnabled: true,
  85057. };
  85058. };
  85059. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  85060. /**
  85061. * Gets the root mesh created by the helper.
  85062. */
  85063. get: function () {
  85064. return this._rootMesh;
  85065. },
  85066. enumerable: true,
  85067. configurable: true
  85068. });
  85069. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  85070. /**
  85071. * Gets the skybox created by the helper.
  85072. */
  85073. get: function () {
  85074. return this._skybox;
  85075. },
  85076. enumerable: true,
  85077. configurable: true
  85078. });
  85079. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  85080. /**
  85081. * Gets the skybox texture created by the helper.
  85082. */
  85083. get: function () {
  85084. return this._skyboxTexture;
  85085. },
  85086. enumerable: true,
  85087. configurable: true
  85088. });
  85089. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  85090. /**
  85091. * Gets the skybox material created by the helper.
  85092. */
  85093. get: function () {
  85094. return this._skyboxMaterial;
  85095. },
  85096. enumerable: true,
  85097. configurable: true
  85098. });
  85099. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  85100. /**
  85101. * Gets the ground mesh created by the helper.
  85102. */
  85103. get: function () {
  85104. return this._ground;
  85105. },
  85106. enumerable: true,
  85107. configurable: true
  85108. });
  85109. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  85110. /**
  85111. * Gets the ground texture created by the helper.
  85112. */
  85113. get: function () {
  85114. return this._groundTexture;
  85115. },
  85116. enumerable: true,
  85117. configurable: true
  85118. });
  85119. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  85120. /**
  85121. * Gets the ground mirror created by the helper.
  85122. */
  85123. get: function () {
  85124. return this._groundMirror;
  85125. },
  85126. enumerable: true,
  85127. configurable: true
  85128. });
  85129. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  85130. /**
  85131. * Gets the ground mirror render list to helps pushing the meshes
  85132. * you wish in the ground reflection.
  85133. */
  85134. get: function () {
  85135. if (this._groundMirror) {
  85136. return this._groundMirror.renderList;
  85137. }
  85138. return null;
  85139. },
  85140. enumerable: true,
  85141. configurable: true
  85142. });
  85143. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  85144. /**
  85145. * Gets the ground material created by the helper.
  85146. */
  85147. get: function () {
  85148. return this._groundMaterial;
  85149. },
  85150. enumerable: true,
  85151. configurable: true
  85152. });
  85153. /**
  85154. * Updates the background according to the new options
  85155. * @param options
  85156. */
  85157. EnvironmentHelper.prototype.updateOptions = function (options) {
  85158. var newOptions = __assign({}, this._options, options);
  85159. if (this._ground && !newOptions.createGround) {
  85160. this._ground.dispose();
  85161. this._ground = null;
  85162. }
  85163. if (this._groundMaterial && !newOptions.createGround) {
  85164. this._groundMaterial.dispose();
  85165. this._groundMaterial = null;
  85166. }
  85167. if (this._groundTexture) {
  85168. if (this._options.groundTexture != newOptions.groundTexture) {
  85169. this._groundTexture.dispose();
  85170. this._groundTexture = null;
  85171. }
  85172. }
  85173. if (this._skybox && !newOptions.createSkybox) {
  85174. this._skybox.dispose();
  85175. this._skybox = null;
  85176. }
  85177. if (this._skyboxMaterial && !newOptions.createSkybox) {
  85178. this._skyboxMaterial.dispose();
  85179. this._skyboxMaterial = null;
  85180. }
  85181. if (this._skyboxTexture) {
  85182. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  85183. this._skyboxTexture.dispose();
  85184. this._skyboxTexture = null;
  85185. }
  85186. }
  85187. if (this._groundMirror && !newOptions.enableGroundMirror) {
  85188. this._groundMirror.dispose();
  85189. this._groundMirror = null;
  85190. }
  85191. if (this._scene.environmentTexture) {
  85192. if (this._options.environmentTexture != newOptions.environmentTexture) {
  85193. this._scene.environmentTexture.dispose();
  85194. }
  85195. }
  85196. this._options = newOptions;
  85197. this._setupBackground();
  85198. this._setupImageProcessing();
  85199. };
  85200. /**
  85201. * Sets the primary color of all the available elements.
  85202. * @param color
  85203. */
  85204. EnvironmentHelper.prototype.setMainColor = function (color) {
  85205. if (this.groundMaterial) {
  85206. this.groundMaterial.primaryColor = color;
  85207. }
  85208. if (this.skyboxMaterial) {
  85209. this.skyboxMaterial.primaryColor = color;
  85210. }
  85211. if (this.groundMirror) {
  85212. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  85213. }
  85214. };
  85215. /**
  85216. * Setup the image processing according to the specified options.
  85217. */
  85218. EnvironmentHelper.prototype._setupImageProcessing = function () {
  85219. if (this._options.setupImageProcessing) {
  85220. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  85221. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  85222. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  85223. this._setupEnvironmentTexture();
  85224. }
  85225. };
  85226. /**
  85227. * Setup the environment texture according to the specified options.
  85228. */
  85229. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  85230. if (this._scene.environmentTexture) {
  85231. return;
  85232. }
  85233. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  85234. this._scene.environmentTexture = this._options.environmentTexture;
  85235. return;
  85236. }
  85237. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  85238. this._scene.environmentTexture = environmentTexture;
  85239. };
  85240. /**
  85241. * Setup the background according to the specified options.
  85242. */
  85243. EnvironmentHelper.prototype._setupBackground = function () {
  85244. if (!this._rootMesh) {
  85245. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  85246. }
  85247. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  85248. var sceneSize = this._getSceneSize();
  85249. if (this._options.createGround) {
  85250. this._setupGround(sceneSize);
  85251. this._setupGroundMaterial();
  85252. this._setupGroundDiffuseTexture();
  85253. if (this._options.enableGroundMirror) {
  85254. this._setupGroundMirrorTexture(sceneSize);
  85255. }
  85256. this._setupMirrorInGroundMaterial();
  85257. }
  85258. if (this._options.createSkybox) {
  85259. this._setupSkybox(sceneSize);
  85260. this._setupSkyboxMaterial();
  85261. this._setupSkyboxReflectionTexture();
  85262. }
  85263. this._rootMesh.position.x = sceneSize.rootPosition.x;
  85264. this._rootMesh.position.z = sceneSize.rootPosition.z;
  85265. this._rootMesh.position.y = sceneSize.rootPosition.y;
  85266. };
  85267. /**
  85268. * Get the scene sizes according to the setup.
  85269. */
  85270. EnvironmentHelper.prototype._getSceneSize = function () {
  85271. var groundSize = this._options.groundSize;
  85272. var skyboxSize = this._options.skyboxSize;
  85273. var rootPosition = this._options.rootPosition;
  85274. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  85275. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85276. }
  85277. var sceneExtends = this._scene.getWorldExtends();
  85278. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  85279. if (this._options.sizeAuto) {
  85280. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  85281. this._scene.activeCamera.upperRadiusLimit) {
  85282. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  85283. skyboxSize = groundSize;
  85284. }
  85285. var sceneDiagonalLenght = sceneDiagonal.length();
  85286. if (sceneDiagonalLenght > groundSize) {
  85287. groundSize = sceneDiagonalLenght * 2;
  85288. skyboxSize = groundSize;
  85289. }
  85290. // 10 % bigger.
  85291. groundSize *= 1.1;
  85292. skyboxSize *= 1.5;
  85293. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  85294. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  85295. }
  85296. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85297. };
  85298. /**
  85299. * Setup the ground according to the specified options.
  85300. */
  85301. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  85302. var _this = this;
  85303. if (!this._ground) {
  85304. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  85305. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  85306. this._ground.parent = this._rootMesh;
  85307. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  85308. }
  85309. this._ground.receiveShadows = this._options.enableGroundShadow;
  85310. };
  85311. /**
  85312. * Setup the ground material according to the specified options.
  85313. */
  85314. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  85315. if (!this._groundMaterial) {
  85316. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  85317. }
  85318. this._groundMaterial.alpha = this._options.groundOpacity;
  85319. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  85320. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  85321. this._groundMaterial.primaryLevel = 1;
  85322. this._groundMaterial.primaryColor = this._options.groundColor;
  85323. this._groundMaterial.secondaryLevel = 0;
  85324. this._groundMaterial.tertiaryLevel = 0;
  85325. this._groundMaterial.useRGBColor = false;
  85326. this._groundMaterial.enableNoise = true;
  85327. if (this._ground) {
  85328. this._ground.material = this._groundMaterial;
  85329. }
  85330. };
  85331. /**
  85332. * Setup the ground diffuse texture according to the specified options.
  85333. */
  85334. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  85335. if (!this._groundMaterial) {
  85336. return;
  85337. }
  85338. if (this._groundTexture) {
  85339. return;
  85340. }
  85341. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  85342. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  85343. return;
  85344. }
  85345. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  85346. diffuseTexture.gammaSpace = false;
  85347. diffuseTexture.hasAlpha = true;
  85348. this._groundMaterial.diffuseTexture = diffuseTexture;
  85349. };
  85350. /**
  85351. * Setup the ground mirror texture according to the specified options.
  85352. */
  85353. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  85354. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85355. if (!this._groundMirror) {
  85356. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  85357. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  85358. this._groundMirror.anisotropicFilteringLevel = 1;
  85359. this._groundMirror.wrapU = wrapping;
  85360. this._groundMirror.wrapV = wrapping;
  85361. this._groundMirror.gammaSpace = false;
  85362. if (this._groundMirror.renderList) {
  85363. for (var i = 0; i < this._scene.meshes.length; i++) {
  85364. var mesh = this._scene.meshes[i];
  85365. if (mesh !== this._ground &&
  85366. mesh !== this._skybox &&
  85367. mesh !== this._rootMesh) {
  85368. this._groundMirror.renderList.push(mesh);
  85369. }
  85370. }
  85371. }
  85372. }
  85373. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  85374. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  85375. };
  85376. /**
  85377. * Setup the ground to receive the mirror texture.
  85378. */
  85379. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  85380. if (this._groundMaterial) {
  85381. this._groundMaterial.reflectionTexture = this._groundMirror;
  85382. this._groundMaterial.reflectionFresnel = true;
  85383. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  85384. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  85385. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  85386. }
  85387. };
  85388. /**
  85389. * Setup the skybox according to the specified options.
  85390. */
  85391. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  85392. var _this = this;
  85393. if (!this._skybox) {
  85394. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  85395. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  85396. }
  85397. this._skybox.parent = this._rootMesh;
  85398. };
  85399. /**
  85400. * Setup the skybox material according to the specified options.
  85401. */
  85402. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  85403. if (!this._skybox) {
  85404. return;
  85405. }
  85406. if (!this._skyboxMaterial) {
  85407. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  85408. }
  85409. this._skyboxMaterial.useRGBColor = false;
  85410. this._skyboxMaterial.primaryLevel = 1;
  85411. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  85412. this._skyboxMaterial.secondaryLevel = 0;
  85413. this._skyboxMaterial.tertiaryLevel = 0;
  85414. this._skyboxMaterial.enableNoise = true;
  85415. this._skybox.material = this._skyboxMaterial;
  85416. };
  85417. /**
  85418. * Setup the skybox reflection texture according to the specified options.
  85419. */
  85420. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  85421. if (!this._skyboxMaterial) {
  85422. return;
  85423. }
  85424. if (this._skyboxTexture) {
  85425. return;
  85426. }
  85427. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  85428. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85429. return;
  85430. }
  85431. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  85432. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  85433. this._skyboxTexture.gammaSpace = false;
  85434. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85435. };
  85436. /**
  85437. * Dispose all the elements created by the Helper.
  85438. */
  85439. EnvironmentHelper.prototype.dispose = function () {
  85440. if (this._groundMaterial) {
  85441. this._groundMaterial.dispose(true, true);
  85442. }
  85443. if (this._skyboxMaterial) {
  85444. this._skyboxMaterial.dispose(true, true);
  85445. }
  85446. this._rootMesh.dispose(false);
  85447. };
  85448. /**
  85449. * Default ground texture URL.
  85450. */
  85451. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  85452. /**
  85453. * Default skybox texture URL.
  85454. */
  85455. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  85456. /**
  85457. * Default environment texture URL.
  85458. */
  85459. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  85460. return EnvironmentHelper;
  85461. }());
  85462. BABYLON.EnvironmentHelper = EnvironmentHelper;
  85463. })(BABYLON || (BABYLON = {}));
  85464. //# sourceMappingURL=babylon.environmentHelper.js.map
  85465. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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>\nvoid main(void) {\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#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\ngl_FragColor=color;\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=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 screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\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\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\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\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\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#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\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\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#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  85466. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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#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 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\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 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};"};
  85467. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85468. var BABYLON;
  85469. (function (BABYLON) {
  85470. var GridMaterialDefines = /** @class */ (function (_super) {
  85471. __extends(GridMaterialDefines, _super);
  85472. function GridMaterialDefines() {
  85473. var _this = _super.call(this) || this;
  85474. _this.TRANSPARENT = false;
  85475. _this.FOG = false;
  85476. _this.PREMULTIPLYALPHA = false;
  85477. _this.rebuild();
  85478. return _this;
  85479. }
  85480. return GridMaterialDefines;
  85481. }(BABYLON.MaterialDefines));
  85482. /**
  85483. * The grid materials allows you to wrap any shape with a grid.
  85484. * Colors are customizable.
  85485. */
  85486. var GridMaterial = /** @class */ (function (_super) {
  85487. __extends(GridMaterial, _super);
  85488. /**
  85489. * constructor
  85490. * @param name The name given to the material in order to identify it afterwards.
  85491. * @param scene The scene the material is used in.
  85492. */
  85493. function GridMaterial(name, scene) {
  85494. var _this = _super.call(this, name, scene) || this;
  85495. /**
  85496. * Main color of the grid (e.g. between lines)
  85497. */
  85498. _this.mainColor = BABYLON.Color3.Black();
  85499. /**
  85500. * Color of the grid lines.
  85501. */
  85502. _this.lineColor = BABYLON.Color3.Teal();
  85503. /**
  85504. * The scale of the grid compared to unit.
  85505. */
  85506. _this.gridRatio = 1.0;
  85507. /**
  85508. * Allows setting an offset for the grid lines.
  85509. */
  85510. _this.gridOffset = BABYLON.Vector3.Zero();
  85511. /**
  85512. * The frequency of thicker lines.
  85513. */
  85514. _this.majorUnitFrequency = 10;
  85515. /**
  85516. * The visibility of minor units in the grid.
  85517. */
  85518. _this.minorUnitVisibility = 0.33;
  85519. /**
  85520. * The grid opacity outside of the lines.
  85521. */
  85522. _this.opacity = 1.0;
  85523. /**
  85524. * Determine RBG output is premultiplied by alpha value.
  85525. */
  85526. _this.preMultiplyAlpha = false;
  85527. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  85528. return _this;
  85529. }
  85530. /**
  85531. * Returns wehter or not the grid requires alpha blending.
  85532. */
  85533. GridMaterial.prototype.needAlphaBlending = function () {
  85534. return this.opacity < 1.0;
  85535. };
  85536. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  85537. return this.needAlphaBlending();
  85538. };
  85539. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85540. if (this.isFrozen) {
  85541. if (this._wasPreviouslyReady && subMesh.effect) {
  85542. return true;
  85543. }
  85544. }
  85545. if (!subMesh._materialDefines) {
  85546. subMesh._materialDefines = new GridMaterialDefines();
  85547. }
  85548. var defines = subMesh._materialDefines;
  85549. var scene = this.getScene();
  85550. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85551. if (this._renderId === scene.getRenderId()) {
  85552. return true;
  85553. }
  85554. }
  85555. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  85556. defines.TRANSPARENT = !defines.TRANSPARENT;
  85557. defines.markAsUnprocessed();
  85558. }
  85559. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  85560. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  85561. defines.markAsUnprocessed();
  85562. }
  85563. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  85564. // Get correct effect
  85565. if (defines.isDirty) {
  85566. defines.markAsProcessed();
  85567. scene.resetCachedMaterial();
  85568. // Attributes
  85569. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85570. // Defines
  85571. var join = defines.toString();
  85572. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  85573. }
  85574. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85575. return false;
  85576. }
  85577. this._renderId = scene.getRenderId();
  85578. this._wasPreviouslyReady = true;
  85579. return true;
  85580. };
  85581. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85582. var scene = this.getScene();
  85583. var defines = subMesh._materialDefines;
  85584. if (!defines) {
  85585. return;
  85586. }
  85587. var effect = subMesh.effect;
  85588. if (!effect) {
  85589. return;
  85590. }
  85591. this._activeEffect = effect;
  85592. // Matrices
  85593. this.bindOnlyWorldMatrix(world);
  85594. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  85595. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  85596. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  85597. // Uniforms
  85598. if (this._mustRebind(scene, effect)) {
  85599. this._activeEffect.setColor3("mainColor", this.mainColor);
  85600. this._activeEffect.setColor3("lineColor", this.lineColor);
  85601. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  85602. this._gridControl.x = this.gridRatio;
  85603. this._gridControl.y = Math.round(this.majorUnitFrequency);
  85604. this._gridControl.z = this.minorUnitVisibility;
  85605. this._gridControl.w = this.opacity;
  85606. this._activeEffect.setVector4("gridControl", this._gridControl);
  85607. }
  85608. // Fog
  85609. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85610. this._afterBind(mesh, this._activeEffect);
  85611. };
  85612. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  85613. _super.prototype.dispose.call(this, forceDisposeEffect);
  85614. };
  85615. GridMaterial.prototype.clone = function (name) {
  85616. var _this = this;
  85617. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  85618. };
  85619. GridMaterial.prototype.serialize = function () {
  85620. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85621. serializationObject.customType = "BABYLON.GridMaterial";
  85622. return serializationObject;
  85623. };
  85624. GridMaterial.prototype.getClassName = function () {
  85625. return "GridMaterial";
  85626. };
  85627. GridMaterial.Parse = function (source, scene, rootUrl) {
  85628. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  85629. };
  85630. __decorate([
  85631. BABYLON.serializeAsColor3()
  85632. ], GridMaterial.prototype, "mainColor", void 0);
  85633. __decorate([
  85634. BABYLON.serializeAsColor3()
  85635. ], GridMaterial.prototype, "lineColor", void 0);
  85636. __decorate([
  85637. BABYLON.serialize()
  85638. ], GridMaterial.prototype, "gridRatio", void 0);
  85639. __decorate([
  85640. BABYLON.serializeAsColor3()
  85641. ], GridMaterial.prototype, "gridOffset", void 0);
  85642. __decorate([
  85643. BABYLON.serialize()
  85644. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  85645. __decorate([
  85646. BABYLON.serialize()
  85647. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  85648. __decorate([
  85649. BABYLON.serialize()
  85650. ], GridMaterial.prototype, "opacity", void 0);
  85651. __decorate([
  85652. BABYLON.serialize()
  85653. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  85654. return GridMaterial;
  85655. }(BABYLON.PushMaterial));
  85656. BABYLON.GridMaterial = GridMaterial;
  85657. })(BABYLON || (BABYLON = {}));
  85658. //# sourceMappingURL=babylon.gridmaterial.js.map
  85659. 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}";
  85660. 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}";
  85661. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85662. var BABYLON;
  85663. (function (BABYLON) {
  85664. var GLTFLoaderCoordinateSystemMode;
  85665. (function (GLTFLoaderCoordinateSystemMode) {
  85666. /**
  85667. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  85668. */
  85669. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  85670. /**
  85671. * Sets the useRightHandedSystem flag on the scene.
  85672. */
  85673. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  85674. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  85675. var GLTFLoaderAnimationStartMode;
  85676. (function (GLTFLoaderAnimationStartMode) {
  85677. /**
  85678. * No animation will start.
  85679. */
  85680. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  85681. /**
  85682. * The first animation will start.
  85683. */
  85684. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  85685. /**
  85686. * All animations will start.
  85687. */
  85688. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  85689. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  85690. var GLTFFileLoader = /** @class */ (function () {
  85691. function GLTFFileLoader() {
  85692. // #region Common options
  85693. /**
  85694. * Raised when the asset has been parsed.
  85695. * The data.json property stores the glTF JSON.
  85696. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  85697. */
  85698. this.onParsedObservable = new BABYLON.Observable();
  85699. // #endregion
  85700. // #region V2 options
  85701. /**
  85702. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  85703. */
  85704. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  85705. /**
  85706. * The animation start mode (NONE, FIRST, ALL).
  85707. */
  85708. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  85709. /**
  85710. * Set to true to compile materials before raising the success callback.
  85711. */
  85712. this.compileMaterials = false;
  85713. /**
  85714. * Set to true to also compile materials with clip planes.
  85715. */
  85716. this.useClipPlane = false;
  85717. /**
  85718. * Set to true to compile shadow generators before raising the success callback.
  85719. */
  85720. this.compileShadowGenerators = false;
  85721. /**
  85722. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  85723. */
  85724. this.onMeshLoadedObservable = new BABYLON.Observable();
  85725. /**
  85726. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  85727. */
  85728. this.onTextureLoadedObservable = new BABYLON.Observable();
  85729. /**
  85730. * Raised when the loader creates a material after parsing the glTF properties of the material.
  85731. */
  85732. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85733. /**
  85734. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  85735. * For assets with LODs, raised when all of the LODs are complete.
  85736. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  85737. */
  85738. this.onCompleteObservable = new BABYLON.Observable();
  85739. /**
  85740. * Raised when the loader is disposed.
  85741. */
  85742. this.onDisposeObservable = new BABYLON.Observable();
  85743. // #endregion
  85744. this._loader = null;
  85745. this.name = "gltf";
  85746. this.extensions = {
  85747. ".gltf": { isBinary: false },
  85748. ".glb": { isBinary: true }
  85749. };
  85750. }
  85751. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  85752. set: function (callback) {
  85753. if (this._onParsedObserver) {
  85754. this.onParsedObservable.remove(this._onParsedObserver);
  85755. }
  85756. this._onParsedObserver = this.onParsedObservable.add(callback);
  85757. },
  85758. enumerable: true,
  85759. configurable: true
  85760. });
  85761. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  85762. set: function (callback) {
  85763. if (this._onMeshLoadedObserver) {
  85764. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  85765. }
  85766. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  85767. },
  85768. enumerable: true,
  85769. configurable: true
  85770. });
  85771. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  85772. set: function (callback) {
  85773. if (this._onTextureLoadedObserver) {
  85774. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  85775. }
  85776. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  85777. },
  85778. enumerable: true,
  85779. configurable: true
  85780. });
  85781. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  85782. set: function (callback) {
  85783. if (this._onMaterialLoadedObserver) {
  85784. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  85785. }
  85786. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  85787. },
  85788. enumerable: true,
  85789. configurable: true
  85790. });
  85791. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  85792. set: function (callback) {
  85793. if (this._onCompleteObserver) {
  85794. this.onCompleteObservable.remove(this._onCompleteObserver);
  85795. }
  85796. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  85797. },
  85798. enumerable: true,
  85799. configurable: true
  85800. });
  85801. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  85802. set: function (callback) {
  85803. if (this._onDisposeObserver) {
  85804. this.onDisposeObservable.remove(this._onDisposeObserver);
  85805. }
  85806. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85807. },
  85808. enumerable: true,
  85809. configurable: true
  85810. });
  85811. /**
  85812. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  85813. */
  85814. GLTFFileLoader.prototype.dispose = function () {
  85815. if (this._loader) {
  85816. this._loader.dispose();
  85817. this._loader = null;
  85818. }
  85819. this.onParsedObservable.clear();
  85820. this.onMeshLoadedObservable.clear();
  85821. this.onTextureLoadedObservable.clear();
  85822. this.onMaterialLoadedObservable.clear();
  85823. this.onCompleteObservable.clear();
  85824. this.onDisposeObservable.notifyObservers(this);
  85825. this.onDisposeObservable.clear();
  85826. };
  85827. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85828. try {
  85829. var loaderData = this._parse(data);
  85830. this._loader = this._getLoader(loaderData);
  85831. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85832. }
  85833. catch (e) {
  85834. if (onError) {
  85835. onError(e.message, e);
  85836. }
  85837. else {
  85838. BABYLON.Tools.Error(e.message);
  85839. }
  85840. }
  85841. };
  85842. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85843. try {
  85844. var loaderData = this._parse(data);
  85845. this._loader = this._getLoader(loaderData);
  85846. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85847. }
  85848. catch (e) {
  85849. if (onError) {
  85850. onError(e.message, e);
  85851. }
  85852. else {
  85853. BABYLON.Tools.Error(e.message);
  85854. }
  85855. }
  85856. };
  85857. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85858. try {
  85859. var loaderData = this._parse(data);
  85860. this._loader = this._getLoader(loaderData);
  85861. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  85862. var container = new BABYLON.AssetContainer(scene);
  85863. Array.prototype.push.apply(container.meshes, meshes);
  85864. Array.prototype.push.apply(container.particleSystems, particleSystems);
  85865. Array.prototype.push.apply(container.skeletons, skeletons);
  85866. container.removeAllFromScene();
  85867. onSuccess(container);
  85868. }, onProgress, onError);
  85869. }
  85870. catch (e) {
  85871. if (onError) {
  85872. onError(e.message, e);
  85873. }
  85874. else {
  85875. BABYLON.Tools.Error(e.message);
  85876. }
  85877. }
  85878. };
  85879. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  85880. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  85881. };
  85882. GLTFFileLoader.prototype.createPlugin = function () {
  85883. return new GLTFFileLoader();
  85884. };
  85885. GLTFFileLoader.prototype._parse = function (data) {
  85886. var parsedData;
  85887. if (data instanceof ArrayBuffer) {
  85888. parsedData = GLTFFileLoader._parseBinary(data);
  85889. }
  85890. else {
  85891. parsedData = {
  85892. json: JSON.parse(data),
  85893. bin: null
  85894. };
  85895. }
  85896. this.onParsedObservable.notifyObservers(parsedData);
  85897. return parsedData;
  85898. };
  85899. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  85900. var _this = this;
  85901. var loaderVersion = { major: 2, minor: 0 };
  85902. var asset = loaderData.json.asset || {};
  85903. var version = GLTFFileLoader._parseVersion(asset.version);
  85904. if (!version) {
  85905. throw new Error("Invalid version: " + asset.version);
  85906. }
  85907. if (asset.minVersion !== undefined) {
  85908. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  85909. if (!minVersion) {
  85910. throw new Error("Invalid minimum version: " + asset.minVersion);
  85911. }
  85912. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85913. throw new Error("Incompatible minimum version: " + asset.minVersion);
  85914. }
  85915. }
  85916. var createLoaders = {
  85917. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  85918. 2: GLTFFileLoader.CreateGLTFLoaderV2
  85919. };
  85920. var createLoader = createLoaders[version.major];
  85921. if (!createLoader) {
  85922. throw new Error("Unsupported version: " + asset.version);
  85923. }
  85924. var loader = createLoader();
  85925. loader.coordinateSystemMode = this.coordinateSystemMode;
  85926. loader.animationStartMode = this.animationStartMode;
  85927. loader.compileMaterials = this.compileMaterials;
  85928. loader.useClipPlane = this.useClipPlane;
  85929. loader.compileShadowGenerators = this.compileShadowGenerators;
  85930. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  85931. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  85932. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  85933. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  85934. return loader;
  85935. };
  85936. GLTFFileLoader._parseBinary = function (data) {
  85937. var Binary = {
  85938. Magic: 0x46546C67
  85939. };
  85940. var binaryReader = new BinaryReader(data);
  85941. var magic = binaryReader.readUint32();
  85942. if (magic !== Binary.Magic) {
  85943. throw new Error("Unexpected magic: " + magic);
  85944. }
  85945. var version = binaryReader.readUint32();
  85946. switch (version) {
  85947. case 1: return GLTFFileLoader._parseV1(binaryReader);
  85948. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85949. }
  85950. throw new Error("Unsupported version: " + version);
  85951. };
  85952. GLTFFileLoader._parseV1 = function (binaryReader) {
  85953. var ContentFormat = {
  85954. JSON: 0
  85955. };
  85956. var length = binaryReader.readUint32();
  85957. if (length != binaryReader.getLength()) {
  85958. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85959. }
  85960. var contentLength = binaryReader.readUint32();
  85961. var contentFormat = binaryReader.readUint32();
  85962. var content;
  85963. switch (contentFormat) {
  85964. case ContentFormat.JSON: {
  85965. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  85966. break;
  85967. }
  85968. default: {
  85969. throw new Error("Unexpected content format: " + contentFormat);
  85970. }
  85971. }
  85972. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  85973. var body = binaryReader.readUint8Array(bytesRemaining);
  85974. return {
  85975. json: content,
  85976. bin: body
  85977. };
  85978. };
  85979. GLTFFileLoader._parseV2 = function (binaryReader) {
  85980. var ChunkFormat = {
  85981. JSON: 0x4E4F534A,
  85982. BIN: 0x004E4942
  85983. };
  85984. var length = binaryReader.readUint32();
  85985. if (length !== binaryReader.getLength()) {
  85986. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85987. }
  85988. // JSON chunk
  85989. var chunkLength = binaryReader.readUint32();
  85990. var chunkFormat = binaryReader.readUint32();
  85991. if (chunkFormat !== ChunkFormat.JSON) {
  85992. throw new Error("First chunk format is not JSON");
  85993. }
  85994. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  85995. // Look for BIN chunk
  85996. var bin = null;
  85997. while (binaryReader.getPosition() < binaryReader.getLength()) {
  85998. var chunkLength_1 = binaryReader.readUint32();
  85999. var chunkFormat_1 = binaryReader.readUint32();
  86000. switch (chunkFormat_1) {
  86001. case ChunkFormat.JSON: {
  86002. throw new Error("Unexpected JSON chunk");
  86003. }
  86004. case ChunkFormat.BIN: {
  86005. bin = binaryReader.readUint8Array(chunkLength_1);
  86006. break;
  86007. }
  86008. default: {
  86009. // ignore unrecognized chunkFormat
  86010. binaryReader.skipBytes(chunkLength_1);
  86011. break;
  86012. }
  86013. }
  86014. }
  86015. return {
  86016. json: json,
  86017. bin: bin
  86018. };
  86019. };
  86020. GLTFFileLoader._parseVersion = function (version) {
  86021. if (version === "1.0" || version === "1.0.1") {
  86022. return {
  86023. major: 1,
  86024. minor: 0
  86025. };
  86026. }
  86027. var match = (version + "").match(/^(\d+)\.(\d+)/);
  86028. if (!match) {
  86029. return null;
  86030. }
  86031. return {
  86032. major: parseInt(match[1]),
  86033. minor: parseInt(match[2])
  86034. };
  86035. };
  86036. GLTFFileLoader._compareVersion = function (a, b) {
  86037. if (a.major > b.major)
  86038. return 1;
  86039. if (a.major < b.major)
  86040. return -1;
  86041. if (a.minor > b.minor)
  86042. return 1;
  86043. if (a.minor < b.minor)
  86044. return -1;
  86045. return 0;
  86046. };
  86047. GLTFFileLoader._decodeBufferToText = function (buffer) {
  86048. var result = "";
  86049. var length = buffer.byteLength;
  86050. for (var i = 0; i < length; i++) {
  86051. result += String.fromCharCode(buffer[i]);
  86052. }
  86053. return result;
  86054. };
  86055. // #endregion
  86056. // #region V1 options
  86057. GLTFFileLoader.IncrementalLoading = true;
  86058. GLTFFileLoader.HomogeneousCoordinates = false;
  86059. return GLTFFileLoader;
  86060. }());
  86061. BABYLON.GLTFFileLoader = GLTFFileLoader;
  86062. var BinaryReader = /** @class */ (function () {
  86063. function BinaryReader(arrayBuffer) {
  86064. this._arrayBuffer = arrayBuffer;
  86065. this._dataView = new DataView(arrayBuffer);
  86066. this._byteOffset = 0;
  86067. }
  86068. BinaryReader.prototype.getPosition = function () {
  86069. return this._byteOffset;
  86070. };
  86071. BinaryReader.prototype.getLength = function () {
  86072. return this._arrayBuffer.byteLength;
  86073. };
  86074. BinaryReader.prototype.readUint32 = function () {
  86075. var value = this._dataView.getUint32(this._byteOffset, true);
  86076. this._byteOffset += 4;
  86077. return value;
  86078. };
  86079. BinaryReader.prototype.readUint8Array = function (length) {
  86080. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  86081. this._byteOffset += length;
  86082. return value;
  86083. };
  86084. BinaryReader.prototype.skipBytes = function (length) {
  86085. this._byteOffset += length;
  86086. };
  86087. return BinaryReader;
  86088. }());
  86089. if (BABYLON.SceneLoader) {
  86090. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  86091. }
  86092. })(BABYLON || (BABYLON = {}));
  86093. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  86094. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86095. var BABYLON;
  86096. (function (BABYLON) {
  86097. var GLTF1;
  86098. (function (GLTF1) {
  86099. /**
  86100. * Enums
  86101. */
  86102. var EComponentType;
  86103. (function (EComponentType) {
  86104. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  86105. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86106. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  86107. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86108. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  86109. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  86110. var EShaderType;
  86111. (function (EShaderType) {
  86112. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  86113. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  86114. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  86115. var EParameterType;
  86116. (function (EParameterType) {
  86117. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  86118. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86119. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  86120. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86121. EParameterType[EParameterType["INT"] = 5124] = "INT";
  86122. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  86123. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  86124. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  86125. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  86126. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  86127. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  86128. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  86129. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  86130. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  86131. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  86132. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  86133. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  86134. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  86135. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  86136. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  86137. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  86138. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  86139. var ETextureWrapMode;
  86140. (function (ETextureWrapMode) {
  86141. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  86142. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  86143. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  86144. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  86145. var ETextureFilterType;
  86146. (function (ETextureFilterType) {
  86147. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  86148. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  86149. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  86150. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  86151. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  86152. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  86153. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  86154. var ETextureFormat;
  86155. (function (ETextureFormat) {
  86156. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  86157. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  86158. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  86159. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  86160. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  86161. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  86162. var ECullingType;
  86163. (function (ECullingType) {
  86164. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  86165. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  86166. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  86167. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  86168. var EBlendingFunction;
  86169. (function (EBlendingFunction) {
  86170. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  86171. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  86172. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  86173. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  86174. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  86175. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  86176. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  86177. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  86178. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  86179. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  86180. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  86181. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  86182. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  86183. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  86184. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  86185. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  86186. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86187. })(BABYLON || (BABYLON = {}));
  86188. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  86189. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86190. var BABYLON;
  86191. (function (BABYLON) {
  86192. var GLTF1;
  86193. (function (GLTF1) {
  86194. /**
  86195. * Tokenizer. Used for shaders compatibility
  86196. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  86197. */
  86198. var ETokenType;
  86199. (function (ETokenType) {
  86200. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  86201. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  86202. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  86203. })(ETokenType || (ETokenType = {}));
  86204. var Tokenizer = /** @class */ (function () {
  86205. function Tokenizer(toParse) {
  86206. this._pos = 0;
  86207. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  86208. this._toParse = toParse;
  86209. this._maxPos = toParse.length;
  86210. }
  86211. Tokenizer.prototype.getNextToken = function () {
  86212. if (this.isEnd())
  86213. return ETokenType.END_OF_INPUT;
  86214. this.currentString = this.read();
  86215. this.currentToken = ETokenType.UNKNOWN;
  86216. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  86217. this.currentToken = ETokenType.IDENTIFIER;
  86218. this.currentIdentifier = this.currentString;
  86219. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  86220. this.currentIdentifier += this.currentString;
  86221. this.forward();
  86222. }
  86223. }
  86224. return this.currentToken;
  86225. };
  86226. Tokenizer.prototype.peek = function () {
  86227. return this._toParse[this._pos];
  86228. };
  86229. Tokenizer.prototype.read = function () {
  86230. return this._toParse[this._pos++];
  86231. };
  86232. Tokenizer.prototype.forward = function () {
  86233. this._pos++;
  86234. };
  86235. Tokenizer.prototype.isEnd = function () {
  86236. return this._pos >= this._maxPos;
  86237. };
  86238. return Tokenizer;
  86239. }());
  86240. /**
  86241. * Values
  86242. */
  86243. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  86244. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  86245. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  86246. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  86247. /**
  86248. * Parse
  86249. */
  86250. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  86251. for (var buf in parsedBuffers) {
  86252. var parsedBuffer = parsedBuffers[buf];
  86253. gltfRuntime.buffers[buf] = parsedBuffer;
  86254. gltfRuntime.buffersCount++;
  86255. }
  86256. };
  86257. var parseShaders = function (parsedShaders, gltfRuntime) {
  86258. for (var sha in parsedShaders) {
  86259. var parsedShader = parsedShaders[sha];
  86260. gltfRuntime.shaders[sha] = parsedShader;
  86261. gltfRuntime.shaderscount++;
  86262. }
  86263. };
  86264. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  86265. for (var object in parsedObjects) {
  86266. var parsedObject = parsedObjects[object];
  86267. gltfRuntime[runtimeProperty][object] = parsedObject;
  86268. }
  86269. };
  86270. /**
  86271. * Utils
  86272. */
  86273. var normalizeUVs = function (buffer) {
  86274. if (!buffer) {
  86275. return;
  86276. }
  86277. for (var i = 0; i < buffer.length / 2; i++) {
  86278. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  86279. }
  86280. };
  86281. var getAttribute = function (attributeParameter) {
  86282. if (attributeParameter.semantic === "NORMAL") {
  86283. return "normal";
  86284. }
  86285. else if (attributeParameter.semantic === "POSITION") {
  86286. return "position";
  86287. }
  86288. else if (attributeParameter.semantic === "JOINT") {
  86289. return "matricesIndices";
  86290. }
  86291. else if (attributeParameter.semantic === "WEIGHT") {
  86292. return "matricesWeights";
  86293. }
  86294. else if (attributeParameter.semantic === "COLOR") {
  86295. return "color";
  86296. }
  86297. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  86298. var channel = Number(attributeParameter.semantic.split("_")[1]);
  86299. return "uv" + (channel === 0 ? "" : channel + 1);
  86300. }
  86301. return null;
  86302. };
  86303. /**
  86304. * Loads and creates animations
  86305. */
  86306. var loadAnimations = function (gltfRuntime) {
  86307. for (var anim in gltfRuntime.animations) {
  86308. var animation = gltfRuntime.animations[anim];
  86309. if (!animation.channels || !animation.samplers) {
  86310. continue;
  86311. }
  86312. var lastAnimation = null;
  86313. for (var i = 0; i < animation.channels.length; i++) {
  86314. // Get parameters and load buffers
  86315. var channel = animation.channels[i];
  86316. var sampler = animation.samplers[channel.sampler];
  86317. if (!sampler) {
  86318. continue;
  86319. }
  86320. var inputData = null;
  86321. var outputData = null;
  86322. if (animation.parameters) {
  86323. inputData = animation.parameters[sampler.input];
  86324. outputData = animation.parameters[sampler.output];
  86325. }
  86326. else {
  86327. inputData = sampler.input;
  86328. outputData = sampler.output;
  86329. }
  86330. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  86331. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  86332. var targetID = channel.target.id;
  86333. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  86334. if (targetNode === null) {
  86335. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  86336. }
  86337. if (targetNode === null) {
  86338. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  86339. continue;
  86340. }
  86341. var isBone = targetNode instanceof BABYLON.Bone;
  86342. // Get target path (position, rotation or scaling)
  86343. var targetPath = channel.target.path;
  86344. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  86345. if (targetPathIndex !== -1) {
  86346. targetPath = babylonAnimationPaths[targetPathIndex];
  86347. }
  86348. // Determine animation type
  86349. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  86350. if (!isBone) {
  86351. if (targetPath === "rotationQuaternion") {
  86352. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  86353. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  86354. }
  86355. else {
  86356. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  86357. }
  86358. }
  86359. // Create animation and key frames
  86360. var babylonAnimation = null;
  86361. var keys = [];
  86362. var arrayOffset = 0;
  86363. var modifyKey = false;
  86364. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  86365. babylonAnimation = lastAnimation;
  86366. modifyKey = true;
  86367. }
  86368. if (!modifyKey) {
  86369. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86370. }
  86371. // For each frame
  86372. for (var j = 0; j < bufferInput.length; j++) {
  86373. var value = null;
  86374. if (targetPath === "rotationQuaternion") {
  86375. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  86376. arrayOffset += 4;
  86377. }
  86378. else {
  86379. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  86380. arrayOffset += 3;
  86381. }
  86382. if (isBone) {
  86383. var bone = targetNode;
  86384. var translation = BABYLON.Vector3.Zero();
  86385. var rotationQuaternion = new BABYLON.Quaternion();
  86386. var scaling = BABYLON.Vector3.Zero();
  86387. // Warning on decompose
  86388. var mat = bone.getBaseMatrix();
  86389. if (modifyKey && lastAnimation) {
  86390. mat = lastAnimation.getKeys()[j].value;
  86391. }
  86392. mat.decompose(scaling, rotationQuaternion, translation);
  86393. if (targetPath === "position") {
  86394. translation = value;
  86395. }
  86396. else if (targetPath === "rotationQuaternion") {
  86397. rotationQuaternion = value;
  86398. }
  86399. else {
  86400. scaling = value;
  86401. }
  86402. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  86403. }
  86404. if (!modifyKey) {
  86405. keys.push({
  86406. frame: bufferInput[j],
  86407. value: value
  86408. });
  86409. }
  86410. else if (lastAnimation) {
  86411. lastAnimation.getKeys()[j].value = value;
  86412. }
  86413. }
  86414. // Finish
  86415. if (!modifyKey && babylonAnimation) {
  86416. babylonAnimation.setKeys(keys);
  86417. targetNode.animations.push(babylonAnimation);
  86418. }
  86419. lastAnimation = babylonAnimation;
  86420. gltfRuntime.scene.stopAnimation(targetNode);
  86421. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  86422. }
  86423. }
  86424. };
  86425. /**
  86426. * Returns the bones transformation matrix
  86427. */
  86428. var configureBoneTransformation = function (node) {
  86429. var mat = null;
  86430. if (node.translation || node.rotation || node.scale) {
  86431. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  86432. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  86433. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  86434. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  86435. }
  86436. else {
  86437. mat = BABYLON.Matrix.FromArray(node.matrix);
  86438. }
  86439. return mat;
  86440. };
  86441. /**
  86442. * Returns the parent bone
  86443. */
  86444. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  86445. // Try to find
  86446. for (var i = 0; i < newSkeleton.bones.length; i++) {
  86447. if (newSkeleton.bones[i].name === jointName) {
  86448. return newSkeleton.bones[i];
  86449. }
  86450. }
  86451. // Not found, search in gltf nodes
  86452. var nodes = gltfRuntime.nodes;
  86453. for (var nde in nodes) {
  86454. var node = nodes[nde];
  86455. if (!node.jointName) {
  86456. continue;
  86457. }
  86458. var children = node.children;
  86459. for (var i = 0; i < children.length; i++) {
  86460. var child = gltfRuntime.nodes[children[i]];
  86461. if (!child.jointName) {
  86462. continue;
  86463. }
  86464. if (child.jointName === jointName) {
  86465. var mat = configureBoneTransformation(node);
  86466. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  86467. bone.id = nde;
  86468. return bone;
  86469. }
  86470. }
  86471. }
  86472. return null;
  86473. };
  86474. /**
  86475. * Returns the appropriate root node
  86476. */
  86477. var getNodeToRoot = function (nodesToRoot, id) {
  86478. for (var i = 0; i < nodesToRoot.length; i++) {
  86479. var nodeToRoot = nodesToRoot[i];
  86480. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  86481. var child = nodeToRoot.node.children[j];
  86482. if (child === id) {
  86483. return nodeToRoot.bone;
  86484. }
  86485. }
  86486. }
  86487. return null;
  86488. };
  86489. /**
  86490. * Returns the node with the joint name
  86491. */
  86492. var getJointNode = function (gltfRuntime, jointName) {
  86493. var nodes = gltfRuntime.nodes;
  86494. var node = nodes[jointName];
  86495. if (node) {
  86496. return {
  86497. node: node,
  86498. id: jointName
  86499. };
  86500. }
  86501. for (var nde in nodes) {
  86502. node = nodes[nde];
  86503. if (node.jointName === jointName) {
  86504. return {
  86505. node: node,
  86506. id: nde
  86507. };
  86508. }
  86509. }
  86510. return null;
  86511. };
  86512. /**
  86513. * Checks if a nodes is in joints
  86514. */
  86515. var nodeIsInJoints = function (skins, id) {
  86516. for (var i = 0; i < skins.jointNames.length; i++) {
  86517. if (skins.jointNames[i] === id) {
  86518. return true;
  86519. }
  86520. }
  86521. return false;
  86522. };
  86523. /**
  86524. * Fills the nodes to root for bones and builds hierarchy
  86525. */
  86526. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  86527. // Creates nodes for root
  86528. for (var nde in gltfRuntime.nodes) {
  86529. var node = gltfRuntime.nodes[nde];
  86530. var id = nde;
  86531. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  86532. continue;
  86533. }
  86534. // Create node to root bone
  86535. var mat = configureBoneTransformation(node);
  86536. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  86537. bone.id = id;
  86538. nodesToRoot.push({ bone: bone, node: node, id: id });
  86539. }
  86540. // Parenting
  86541. for (var i = 0; i < nodesToRoot.length; i++) {
  86542. var nodeToRoot = nodesToRoot[i];
  86543. var children = nodeToRoot.node.children;
  86544. for (var j = 0; j < children.length; j++) {
  86545. var child = null;
  86546. for (var k = 0; k < nodesToRoot.length; k++) {
  86547. if (nodesToRoot[k].id === children[j]) {
  86548. child = nodesToRoot[k];
  86549. break;
  86550. }
  86551. }
  86552. if (child) {
  86553. child.bone._parent = nodeToRoot.bone;
  86554. nodeToRoot.bone.children.push(child.bone);
  86555. }
  86556. }
  86557. }
  86558. };
  86559. /**
  86560. * Imports a skeleton
  86561. */
  86562. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  86563. if (!newSkeleton) {
  86564. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  86565. }
  86566. if (!skins.babylonSkeleton) {
  86567. return newSkeleton;
  86568. }
  86569. // Find the root bones
  86570. var nodesToRoot = [];
  86571. var nodesToRootToAdd = [];
  86572. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  86573. newSkeleton.bones = [];
  86574. // Joints
  86575. for (var i = 0; i < skins.jointNames.length; i++) {
  86576. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86577. if (!jointNode) {
  86578. continue;
  86579. }
  86580. var node = jointNode.node;
  86581. if (!node) {
  86582. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  86583. continue;
  86584. }
  86585. var id = jointNode.id;
  86586. // Optimize, if the bone already exists...
  86587. var existingBone = gltfRuntime.scene.getBoneByID(id);
  86588. if (existingBone) {
  86589. newSkeleton.bones.push(existingBone);
  86590. continue;
  86591. }
  86592. // Search for parent bone
  86593. var foundBone = false;
  86594. var parentBone = null;
  86595. for (var j = 0; j < i; j++) {
  86596. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  86597. if (!jointNode_1) {
  86598. continue;
  86599. }
  86600. var joint = jointNode_1.node;
  86601. if (!joint) {
  86602. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  86603. continue;
  86604. }
  86605. var children = joint.children;
  86606. if (!children) {
  86607. continue;
  86608. }
  86609. foundBone = false;
  86610. for (var k = 0; k < children.length; k++) {
  86611. if (children[k] === id) {
  86612. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  86613. foundBone = true;
  86614. break;
  86615. }
  86616. }
  86617. if (foundBone) {
  86618. break;
  86619. }
  86620. }
  86621. // Create bone
  86622. var mat = configureBoneTransformation(node);
  86623. if (!parentBone && nodesToRoot.length > 0) {
  86624. parentBone = getNodeToRoot(nodesToRoot, id);
  86625. if (parentBone) {
  86626. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  86627. nodesToRootToAdd.push(parentBone);
  86628. }
  86629. }
  86630. }
  86631. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  86632. bone.id = id;
  86633. }
  86634. // Polish
  86635. var bones = newSkeleton.bones;
  86636. newSkeleton.bones = [];
  86637. for (var i = 0; i < skins.jointNames.length; i++) {
  86638. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86639. if (!jointNode) {
  86640. continue;
  86641. }
  86642. for (var j = 0; j < bones.length; j++) {
  86643. if (bones[j].id === jointNode.id) {
  86644. newSkeleton.bones.push(bones[j]);
  86645. break;
  86646. }
  86647. }
  86648. }
  86649. newSkeleton.prepare();
  86650. // Finish
  86651. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  86652. newSkeleton.bones.push(nodesToRootToAdd[i]);
  86653. }
  86654. return newSkeleton;
  86655. };
  86656. /**
  86657. * Imports a mesh and its geometries
  86658. */
  86659. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  86660. if (!newMesh) {
  86661. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86662. newMesh.id = id;
  86663. }
  86664. if (!node.babylonNode) {
  86665. return newMesh;
  86666. }
  86667. var subMaterials = [];
  86668. var vertexData = new BABYLON.VertexData();
  86669. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  86670. var verticesStarts = new Array();
  86671. var verticesCounts = new Array();
  86672. var indexStarts = new Array();
  86673. var indexCounts = new Array();
  86674. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86675. var meshID = meshes[meshIndex];
  86676. var mesh = gltfRuntime.meshes[meshID];
  86677. if (!mesh) {
  86678. continue;
  86679. }
  86680. // Positions, normals and UVs
  86681. for (var i = 0; i < mesh.primitives.length; i++) {
  86682. // Temporary vertex data
  86683. var tempVertexData = new BABYLON.VertexData();
  86684. var primitive = mesh.primitives[i];
  86685. if (primitive.mode !== 4) {
  86686. // continue;
  86687. }
  86688. var attributes = primitive.attributes;
  86689. var accessor = null;
  86690. var buffer = null;
  86691. // Set positions, normal and uvs
  86692. for (var semantic in attributes) {
  86693. // Link accessor and buffer view
  86694. accessor = gltfRuntime.accessors[attributes[semantic]];
  86695. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86696. if (semantic === "NORMAL") {
  86697. tempVertexData.normals = new Float32Array(buffer.length);
  86698. tempVertexData.normals.set(buffer);
  86699. }
  86700. else if (semantic === "POSITION") {
  86701. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  86702. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  86703. for (var j = 0; j < buffer.length; j += 4) {
  86704. tempVertexData.positions[j] = buffer[j];
  86705. tempVertexData.positions[j + 1] = buffer[j + 1];
  86706. tempVertexData.positions[j + 2] = buffer[j + 2];
  86707. }
  86708. }
  86709. else {
  86710. tempVertexData.positions = new Float32Array(buffer.length);
  86711. tempVertexData.positions.set(buffer);
  86712. }
  86713. verticesCounts.push(tempVertexData.positions.length);
  86714. }
  86715. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  86716. var channel = Number(semantic.split("_")[1]);
  86717. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  86718. var uvs = new Float32Array(buffer.length);
  86719. uvs.set(buffer);
  86720. normalizeUVs(uvs);
  86721. tempVertexData.set(uvs, uvKind);
  86722. }
  86723. else if (semantic === "JOINT") {
  86724. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  86725. tempVertexData.matricesIndices.set(buffer);
  86726. }
  86727. else if (semantic === "WEIGHT") {
  86728. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  86729. tempVertexData.matricesWeights.set(buffer);
  86730. }
  86731. else if (semantic === "COLOR") {
  86732. tempVertexData.colors = new Float32Array(buffer.length);
  86733. tempVertexData.colors.set(buffer);
  86734. }
  86735. }
  86736. // Indices
  86737. accessor = gltfRuntime.accessors[primitive.indices];
  86738. if (accessor) {
  86739. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86740. tempVertexData.indices = new Int32Array(buffer.length);
  86741. tempVertexData.indices.set(buffer);
  86742. indexCounts.push(tempVertexData.indices.length);
  86743. }
  86744. else {
  86745. // Set indices on the fly
  86746. var indices = [];
  86747. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  86748. indices.push(j);
  86749. }
  86750. tempVertexData.indices = new Int32Array(indices);
  86751. indexCounts.push(tempVertexData.indices.length);
  86752. }
  86753. vertexData.merge(tempVertexData);
  86754. // Sub material
  86755. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  86756. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  86757. // Update vertices start and index start
  86758. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  86759. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  86760. }
  86761. }
  86762. var material;
  86763. if (subMaterials.length > 1) {
  86764. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  86765. material.subMaterials = subMaterials;
  86766. }
  86767. else {
  86768. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  86769. }
  86770. if (subMaterials.length === 1) {
  86771. material = subMaterials[0];
  86772. }
  86773. if (!newMesh.material) {
  86774. newMesh.material = material;
  86775. }
  86776. // Apply geometry
  86777. geometry.setAllVerticesData(vertexData, false);
  86778. newMesh.computeWorldMatrix(true);
  86779. // Apply submeshes
  86780. newMesh.subMeshes = [];
  86781. var index = 0;
  86782. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86783. var meshID = meshes[meshIndex];
  86784. var mesh = gltfRuntime.meshes[meshID];
  86785. if (!mesh) {
  86786. continue;
  86787. }
  86788. for (var i = 0; i < mesh.primitives.length; i++) {
  86789. if (mesh.primitives[i].mode !== 4) {
  86790. //continue;
  86791. }
  86792. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  86793. index++;
  86794. }
  86795. }
  86796. // Finish
  86797. return newMesh;
  86798. };
  86799. /**
  86800. * Configure node transformation from position, rotation and scaling
  86801. */
  86802. var configureNode = function (newNode, position, rotation, scaling) {
  86803. if (newNode.position) {
  86804. newNode.position = position;
  86805. }
  86806. if (newNode.rotationQuaternion || newNode.rotation) {
  86807. newNode.rotationQuaternion = rotation;
  86808. }
  86809. if (newNode.scaling) {
  86810. newNode.scaling = scaling;
  86811. }
  86812. };
  86813. /**
  86814. * Configures node from transformation matrix
  86815. */
  86816. var configureNodeFromMatrix = function (newNode, node, parent) {
  86817. if (node.matrix) {
  86818. var position = new BABYLON.Vector3(0, 0, 0);
  86819. var rotation = new BABYLON.Quaternion();
  86820. var scaling = new BABYLON.Vector3(0, 0, 0);
  86821. var mat = BABYLON.Matrix.FromArray(node.matrix);
  86822. mat.decompose(scaling, rotation, position);
  86823. configureNode(newNode, position, rotation, scaling);
  86824. }
  86825. else if (node.translation && node.rotation && node.scale) {
  86826. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  86827. }
  86828. newNode.computeWorldMatrix(true);
  86829. };
  86830. /**
  86831. * Imports a node
  86832. */
  86833. var importNode = function (gltfRuntime, node, id, parent) {
  86834. var lastNode = null;
  86835. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  86836. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  86837. return null;
  86838. }
  86839. }
  86840. // Meshes
  86841. if (node.skin) {
  86842. if (node.meshes) {
  86843. var skin = gltfRuntime.skins[node.skin];
  86844. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  86845. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  86846. if (newMesh.skeleton === null) {
  86847. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  86848. if (!skin.babylonSkeleton) {
  86849. skin.babylonSkeleton = newMesh.skeleton;
  86850. }
  86851. }
  86852. lastNode = newMesh;
  86853. }
  86854. }
  86855. else if (node.meshes) {
  86856. /**
  86857. * Improve meshes property
  86858. */
  86859. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  86860. lastNode = newMesh;
  86861. }
  86862. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86863. var light = gltfRuntime.lights[node.light];
  86864. if (light) {
  86865. if (light.type === "ambient") {
  86866. var ambienLight = light[light.type];
  86867. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86868. hemiLight.name = node.name || "";
  86869. if (ambienLight.color) {
  86870. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  86871. }
  86872. lastNode = hemiLight;
  86873. }
  86874. else if (light.type === "directional") {
  86875. var directionalLight = light[light.type];
  86876. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86877. dirLight.name = node.name || "";
  86878. if (directionalLight.color) {
  86879. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  86880. }
  86881. lastNode = dirLight;
  86882. }
  86883. else if (light.type === "point") {
  86884. var pointLight = light[light.type];
  86885. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86886. ptLight.name = node.name || "";
  86887. if (pointLight.color) {
  86888. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  86889. }
  86890. lastNode = ptLight;
  86891. }
  86892. else if (light.type === "spot") {
  86893. var spotLight = light[light.type];
  86894. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  86895. spLight.name = node.name || "";
  86896. if (spotLight.color) {
  86897. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  86898. }
  86899. if (spotLight.fallOfAngle) {
  86900. spLight.angle = spotLight.fallOfAngle;
  86901. }
  86902. if (spotLight.fallOffExponent) {
  86903. spLight.exponent = spotLight.fallOffExponent;
  86904. }
  86905. lastNode = spLight;
  86906. }
  86907. }
  86908. }
  86909. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86910. var camera = gltfRuntime.cameras[node.camera];
  86911. if (camera) {
  86912. if (camera.type === "orthographic") {
  86913. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86914. orthoCamera.name = node.name || "";
  86915. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  86916. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86917. lastNode = orthoCamera;
  86918. }
  86919. else if (camera.type === "perspective") {
  86920. var perspectiveCamera = camera[camera.type];
  86921. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86922. persCamera.name = node.name || "";
  86923. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86924. if (!perspectiveCamera.aspectRatio) {
  86925. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  86926. }
  86927. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  86928. persCamera.maxZ = perspectiveCamera.zfar;
  86929. persCamera.minZ = perspectiveCamera.znear;
  86930. }
  86931. lastNode = persCamera;
  86932. }
  86933. }
  86934. }
  86935. // Empty node
  86936. if (!node.jointName) {
  86937. if (node.babylonNode) {
  86938. return node.babylonNode;
  86939. }
  86940. else if (lastNode === null) {
  86941. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86942. node.babylonNode = dummy;
  86943. lastNode = dummy;
  86944. }
  86945. }
  86946. if (lastNode !== null) {
  86947. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  86948. configureNodeFromMatrix(lastNode, node, parent);
  86949. }
  86950. else {
  86951. var translation = node.translation || [0, 0, 0];
  86952. var rotation = node.rotation || [0, 0, 0, 1];
  86953. var scale = node.scale || [1, 1, 1];
  86954. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  86955. }
  86956. lastNode.updateCache(true);
  86957. node.babylonNode = lastNode;
  86958. }
  86959. return lastNode;
  86960. };
  86961. /**
  86962. * Traverses nodes and creates them
  86963. */
  86964. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  86965. if (meshIncluded === void 0) { meshIncluded = false; }
  86966. var node = gltfRuntime.nodes[id];
  86967. var newNode = null;
  86968. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  86969. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  86970. meshIncluded = true;
  86971. }
  86972. else {
  86973. meshIncluded = false;
  86974. }
  86975. }
  86976. else {
  86977. meshIncluded = true;
  86978. }
  86979. if (!node.jointName && meshIncluded) {
  86980. newNode = importNode(gltfRuntime, node, id, parent);
  86981. if (newNode !== null) {
  86982. newNode.id = id;
  86983. newNode.parent = parent;
  86984. }
  86985. }
  86986. if (node.children) {
  86987. for (var i = 0; i < node.children.length; i++) {
  86988. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  86989. }
  86990. }
  86991. };
  86992. /**
  86993. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  86994. */
  86995. var postLoad = function (gltfRuntime) {
  86996. // Nodes
  86997. var currentScene = gltfRuntime.currentScene;
  86998. if (currentScene) {
  86999. for (var i = 0; i < currentScene.nodes.length; i++) {
  87000. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87001. }
  87002. }
  87003. else {
  87004. for (var thing in gltfRuntime.scenes) {
  87005. currentScene = gltfRuntime.scenes[thing];
  87006. for (var i = 0; i < currentScene.nodes.length; i++) {
  87007. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87008. }
  87009. }
  87010. }
  87011. // Set animations
  87012. loadAnimations(gltfRuntime);
  87013. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  87014. var skeleton = gltfRuntime.scene.skeletons[i];
  87015. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  87016. }
  87017. };
  87018. /**
  87019. * onBind shaderrs callback to set uniforms and matrices
  87020. */
  87021. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  87022. var materialValues = material.values || technique.parameters;
  87023. for (var unif in unTreatedUniforms) {
  87024. var uniform = unTreatedUniforms[unif];
  87025. var type = uniform.type;
  87026. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  87027. if (uniform.semantic && !uniform.source && !uniform.node) {
  87028. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  87029. }
  87030. else if (uniform.semantic && (uniform.source || uniform.node)) {
  87031. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  87032. if (source === null) {
  87033. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  87034. }
  87035. if (source === null) {
  87036. continue;
  87037. }
  87038. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  87039. }
  87040. }
  87041. else {
  87042. var value = materialValues[technique.uniforms[unif]];
  87043. if (!value) {
  87044. continue;
  87045. }
  87046. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  87047. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  87048. if (texture === null || texture === undefined) {
  87049. continue;
  87050. }
  87051. shaderMaterial.getEffect().setTexture(unif, texture);
  87052. }
  87053. else {
  87054. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  87055. }
  87056. }
  87057. }
  87058. onSuccess(shaderMaterial);
  87059. };
  87060. /**
  87061. * Prepare uniforms to send the only one time
  87062. * Loads the appropriate textures
  87063. */
  87064. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  87065. var materialValues = material.values || technique.parameters;
  87066. var techniqueUniforms = technique.uniforms;
  87067. /**
  87068. * Prepare values here (not matrices)
  87069. */
  87070. for (var unif in unTreatedUniforms) {
  87071. var uniform = unTreatedUniforms[unif];
  87072. var type = uniform.type;
  87073. var value = materialValues[techniqueUniforms[unif]];
  87074. if (value === undefined) {
  87075. // In case the value is the same for all materials
  87076. value = uniform.value;
  87077. }
  87078. if (!value) {
  87079. continue;
  87080. }
  87081. var onLoadTexture = function (uniformName) {
  87082. return function (texture) {
  87083. if (uniform.value && uniformName) {
  87084. // Static uniform
  87085. shaderMaterial.setTexture(uniformName, texture);
  87086. delete unTreatedUniforms[uniformName];
  87087. }
  87088. };
  87089. };
  87090. // Texture (sampler2D)
  87091. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  87092. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  87093. }
  87094. else {
  87095. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  87096. // Static uniform
  87097. delete unTreatedUniforms[unif];
  87098. }
  87099. }
  87100. }
  87101. };
  87102. /**
  87103. * Shader compilation failed
  87104. */
  87105. var onShaderCompileError = function (program, shaderMaterial, onError) {
  87106. return function (effect, error) {
  87107. shaderMaterial.dispose(true);
  87108. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  87109. };
  87110. };
  87111. /**
  87112. * Shader compilation success
  87113. */
  87114. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  87115. return function (_) {
  87116. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  87117. shaderMaterial.onBind = function (mesh) {
  87118. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  87119. };
  87120. };
  87121. };
  87122. /**
  87123. * Returns the appropriate uniform if already handled by babylon
  87124. */
  87125. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  87126. for (var unif in technique.uniforms) {
  87127. var uniform = technique.uniforms[unif];
  87128. var uniformParameter = technique.parameters[uniform];
  87129. if (tokenizer.currentIdentifier === unif) {
  87130. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  87131. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  87132. if (transformIndex !== -1) {
  87133. delete unTreatedUniforms[unif];
  87134. return babylonTransforms[transformIndex];
  87135. }
  87136. }
  87137. }
  87138. }
  87139. return tokenizer.currentIdentifier;
  87140. };
  87141. /**
  87142. * All shaders loaded. Create materials one by one
  87143. */
  87144. var importMaterials = function (gltfRuntime) {
  87145. // Create materials
  87146. for (var mat in gltfRuntime.materials) {
  87147. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  87148. }
  87149. };
  87150. /**
  87151. * Implementation of the base glTF spec
  87152. */
  87153. var GLTFLoaderBase = /** @class */ (function () {
  87154. function GLTFLoaderBase() {
  87155. }
  87156. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  87157. var gltfRuntime = {
  87158. extensions: {},
  87159. accessors: {},
  87160. buffers: {},
  87161. bufferViews: {},
  87162. meshes: {},
  87163. lights: {},
  87164. cameras: {},
  87165. nodes: {},
  87166. images: {},
  87167. textures: {},
  87168. shaders: {},
  87169. programs: {},
  87170. samplers: {},
  87171. techniques: {},
  87172. materials: {},
  87173. animations: {},
  87174. skins: {},
  87175. extensionsUsed: [],
  87176. scenes: {},
  87177. buffersCount: 0,
  87178. shaderscount: 0,
  87179. scene: scene,
  87180. rootUrl: rootUrl,
  87181. loadedBufferCount: 0,
  87182. loadedBufferViews: {},
  87183. loadedShaderCount: 0,
  87184. importOnlyMeshes: false,
  87185. dummyNodes: []
  87186. };
  87187. // Parse
  87188. if (parsedData.extensions) {
  87189. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  87190. }
  87191. if (parsedData.extensionsUsed) {
  87192. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  87193. }
  87194. if (parsedData.buffers) {
  87195. parseBuffers(parsedData.buffers, gltfRuntime);
  87196. }
  87197. if (parsedData.bufferViews) {
  87198. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  87199. }
  87200. if (parsedData.accessors) {
  87201. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  87202. }
  87203. if (parsedData.meshes) {
  87204. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  87205. }
  87206. if (parsedData.lights) {
  87207. parseObject(parsedData.lights, "lights", gltfRuntime);
  87208. }
  87209. if (parsedData.cameras) {
  87210. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  87211. }
  87212. if (parsedData.nodes) {
  87213. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  87214. }
  87215. if (parsedData.images) {
  87216. parseObject(parsedData.images, "images", gltfRuntime);
  87217. }
  87218. if (parsedData.textures) {
  87219. parseObject(parsedData.textures, "textures", gltfRuntime);
  87220. }
  87221. if (parsedData.shaders) {
  87222. parseShaders(parsedData.shaders, gltfRuntime);
  87223. }
  87224. if (parsedData.programs) {
  87225. parseObject(parsedData.programs, "programs", gltfRuntime);
  87226. }
  87227. if (parsedData.samplers) {
  87228. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  87229. }
  87230. if (parsedData.techniques) {
  87231. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  87232. }
  87233. if (parsedData.materials) {
  87234. parseObject(parsedData.materials, "materials", gltfRuntime);
  87235. }
  87236. if (parsedData.animations) {
  87237. parseObject(parsedData.animations, "animations", gltfRuntime);
  87238. }
  87239. if (parsedData.skins) {
  87240. parseObject(parsedData.skins, "skins", gltfRuntime);
  87241. }
  87242. if (parsedData.scenes) {
  87243. gltfRuntime.scenes = parsedData.scenes;
  87244. }
  87245. if (parsedData.scene && parsedData.scenes) {
  87246. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  87247. }
  87248. return gltfRuntime;
  87249. };
  87250. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87251. var buffer = gltfRuntime.buffers[id];
  87252. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  87253. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  87254. }
  87255. else {
  87256. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  87257. if (request) {
  87258. onError(request.status + " " + request.statusText);
  87259. }
  87260. });
  87261. }
  87262. };
  87263. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87264. var texture = gltfRuntime.textures[id];
  87265. if (!texture || !texture.source) {
  87266. onError("");
  87267. return;
  87268. }
  87269. if (texture.babylonTexture) {
  87270. onSuccess(null);
  87271. return;
  87272. }
  87273. var source = gltfRuntime.images[texture.source];
  87274. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  87275. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  87276. }
  87277. else {
  87278. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  87279. if (request) {
  87280. onError(request.status + " " + request.statusText);
  87281. }
  87282. });
  87283. }
  87284. };
  87285. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87286. var texture = gltfRuntime.textures[id];
  87287. if (texture.babylonTexture) {
  87288. onSuccess(texture.babylonTexture);
  87289. return;
  87290. }
  87291. var sampler = gltfRuntime.samplers[texture.sampler];
  87292. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  87293. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  87294. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  87295. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  87296. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87297. var blob = new Blob([buffer]);
  87298. var blobURL = URL.createObjectURL(blob);
  87299. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  87300. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  87301. if (sampler.wrapS !== undefined) {
  87302. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  87303. }
  87304. if (sampler.wrapT !== undefined) {
  87305. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  87306. }
  87307. newTexture.name = id;
  87308. texture.babylonTexture = newTexture;
  87309. onSuccess(newTexture);
  87310. };
  87311. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87312. var shader = gltfRuntime.shaders[id];
  87313. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  87314. var shaderString = atob(shader.uri.split(",")[1]);
  87315. onSuccess(shaderString);
  87316. }
  87317. else {
  87318. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  87319. if (request) {
  87320. onError(request.status + " " + request.statusText);
  87321. }
  87322. });
  87323. }
  87324. };
  87325. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87326. var material = gltfRuntime.materials[id];
  87327. if (!material.technique) {
  87328. if (onError) {
  87329. onError("No technique found.");
  87330. }
  87331. return;
  87332. }
  87333. var technique = gltfRuntime.techniques[material.technique];
  87334. if (!technique) {
  87335. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  87336. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  87337. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87338. onSuccess(defaultMaterial);
  87339. return;
  87340. }
  87341. var program = gltfRuntime.programs[technique.program];
  87342. var states = technique.states;
  87343. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  87344. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  87345. var newVertexShader = "";
  87346. var newPixelShader = "";
  87347. var vertexTokenizer = new Tokenizer(vertexShader);
  87348. var pixelTokenizer = new Tokenizer(pixelShader);
  87349. var unTreatedUniforms = {};
  87350. var uniforms = [];
  87351. var attributes = [];
  87352. var samplers = [];
  87353. // Fill uniform, sampler2D and attributes
  87354. for (var unif in technique.uniforms) {
  87355. var uniform = technique.uniforms[unif];
  87356. var uniformParameter = technique.parameters[uniform];
  87357. unTreatedUniforms[unif] = uniformParameter;
  87358. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  87359. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  87360. if (transformIndex !== -1) {
  87361. uniforms.push(babylonTransforms[transformIndex]);
  87362. delete unTreatedUniforms[unif];
  87363. }
  87364. else {
  87365. uniforms.push(unif);
  87366. }
  87367. }
  87368. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  87369. samplers.push(unif);
  87370. }
  87371. else {
  87372. uniforms.push(unif);
  87373. }
  87374. }
  87375. for (var attr in technique.attributes) {
  87376. var attribute = technique.attributes[attr];
  87377. var attributeParameter = technique.parameters[attribute];
  87378. if (attributeParameter.semantic) {
  87379. attributes.push(getAttribute(attributeParameter));
  87380. }
  87381. }
  87382. // Configure vertex shader
  87383. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  87384. var tokenType = vertexTokenizer.currentToken;
  87385. if (tokenType !== ETokenType.IDENTIFIER) {
  87386. newVertexShader += vertexTokenizer.currentString;
  87387. continue;
  87388. }
  87389. var foundAttribute = false;
  87390. for (var attr in technique.attributes) {
  87391. var attribute = technique.attributes[attr];
  87392. var attributeParameter = technique.parameters[attribute];
  87393. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  87394. newVertexShader += getAttribute(attributeParameter);
  87395. foundAttribute = true;
  87396. break;
  87397. }
  87398. }
  87399. if (foundAttribute) {
  87400. continue;
  87401. }
  87402. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  87403. }
  87404. // Configure pixel shader
  87405. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  87406. var tokenType = pixelTokenizer.currentToken;
  87407. if (tokenType !== ETokenType.IDENTIFIER) {
  87408. newPixelShader += pixelTokenizer.currentString;
  87409. continue;
  87410. }
  87411. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  87412. }
  87413. // Create shader material
  87414. var shaderPath = {
  87415. vertex: program.vertexShader + id,
  87416. fragment: program.fragmentShader + id
  87417. };
  87418. var options = {
  87419. attributes: attributes,
  87420. uniforms: uniforms,
  87421. samplers: samplers,
  87422. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  87423. };
  87424. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  87425. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  87426. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  87427. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  87428. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  87429. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87430. if (states && states.functions) {
  87431. var functions = states.functions;
  87432. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  87433. shaderMaterial.backFaceCulling = false;
  87434. }
  87435. var blendFunc = functions.blendFuncSeparate;
  87436. if (blendFunc) {
  87437. 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) {
  87438. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  87439. }
  87440. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87441. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87442. }
  87443. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87444. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  87445. }
  87446. 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) {
  87447. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  87448. }
  87449. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87450. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  87451. }
  87452. 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) {
  87453. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  87454. }
  87455. }
  87456. }
  87457. };
  87458. return GLTFLoaderBase;
  87459. }());
  87460. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  87461. /**
  87462. * glTF V1 Loader
  87463. */
  87464. var GLTFLoader = /** @class */ (function () {
  87465. function GLTFLoader() {
  87466. // #region Stubs for IGLTFLoader interface
  87467. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87468. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87469. this.compileMaterials = false;
  87470. this.useClipPlane = false;
  87471. this.compileShadowGenerators = false;
  87472. this.onDisposeObservable = new BABYLON.Observable();
  87473. this.onMeshLoadedObservable = new BABYLON.Observable();
  87474. this.onTextureLoadedObservable = new BABYLON.Observable();
  87475. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87476. this.onCompleteObservable = new BABYLON.Observable();
  87477. }
  87478. GLTFLoader.RegisterExtension = function (extension) {
  87479. if (GLTFLoader.Extensions[extension.name]) {
  87480. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  87481. return;
  87482. }
  87483. GLTFLoader.Extensions[extension.name] = extension;
  87484. };
  87485. GLTFLoader.prototype.dispose = function () { };
  87486. // #endregion
  87487. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87488. var _this = this;
  87489. scene.useRightHandedSystem = true;
  87490. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87491. gltfRuntime.importOnlyMeshes = true;
  87492. if (meshesNames === "") {
  87493. gltfRuntime.importMeshesNames = [];
  87494. }
  87495. else if (typeof meshesNames === "string") {
  87496. gltfRuntime.importMeshesNames = [meshesNames];
  87497. }
  87498. else if (meshesNames && !(meshesNames instanceof Array)) {
  87499. gltfRuntime.importMeshesNames = [meshesNames];
  87500. }
  87501. else {
  87502. gltfRuntime.importMeshesNames = [];
  87503. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  87504. }
  87505. // Create nodes
  87506. _this._createNodes(gltfRuntime);
  87507. var meshes = new Array();
  87508. var skeletons = new Array();
  87509. // Fill arrays of meshes and skeletons
  87510. for (var nde in gltfRuntime.nodes) {
  87511. var node = gltfRuntime.nodes[nde];
  87512. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  87513. meshes.push(node.babylonNode);
  87514. }
  87515. }
  87516. for (var skl in gltfRuntime.skins) {
  87517. var skin = gltfRuntime.skins[skl];
  87518. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  87519. skeletons.push(skin.babylonSkeleton);
  87520. }
  87521. }
  87522. // Load buffers, shaders, materials, etc.
  87523. _this._loadBuffersAsync(gltfRuntime, function () {
  87524. _this._loadShadersAsync(gltfRuntime, function () {
  87525. importMaterials(gltfRuntime);
  87526. postLoad(gltfRuntime);
  87527. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87528. onSuccess(meshes, [], skeletons);
  87529. }
  87530. });
  87531. }, onProgress);
  87532. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87533. onSuccess(meshes, [], skeletons);
  87534. }
  87535. }, onError);
  87536. return true;
  87537. };
  87538. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87539. var _this = this;
  87540. scene.useRightHandedSystem = true;
  87541. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87542. // Load runtime extensios
  87543. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  87544. // Create nodes
  87545. _this._createNodes(gltfRuntime);
  87546. // Load buffers, shaders, materials, etc.
  87547. _this._loadBuffersAsync(gltfRuntime, function () {
  87548. _this._loadShadersAsync(gltfRuntime, function () {
  87549. importMaterials(gltfRuntime);
  87550. postLoad(gltfRuntime);
  87551. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  87552. onSuccess();
  87553. }
  87554. });
  87555. });
  87556. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  87557. onSuccess();
  87558. }
  87559. }, onError);
  87560. }, onError);
  87561. };
  87562. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  87563. var hasShaders = false;
  87564. var processShader = function (sha, shader) {
  87565. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  87566. gltfRuntime.loadedShaderCount++;
  87567. if (shaderString) {
  87568. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  87569. }
  87570. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  87571. onload();
  87572. }
  87573. }, function () {
  87574. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  87575. });
  87576. };
  87577. for (var sha in gltfRuntime.shaders) {
  87578. hasShaders = true;
  87579. var shader = gltfRuntime.shaders[sha];
  87580. if (shader) {
  87581. processShader.bind(this, sha, shader)();
  87582. }
  87583. else {
  87584. BABYLON.Tools.Error("No shader named: " + sha);
  87585. }
  87586. }
  87587. if (!hasShaders) {
  87588. onload();
  87589. }
  87590. };
  87591. ;
  87592. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  87593. var hasBuffers = false;
  87594. var processBuffer = function (buf, buffer) {
  87595. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  87596. gltfRuntime.loadedBufferCount++;
  87597. if (bufferView) {
  87598. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  87599. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  87600. }
  87601. gltfRuntime.loadedBufferViews[buf] = bufferView;
  87602. }
  87603. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  87604. onLoad();
  87605. }
  87606. }, function () {
  87607. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  87608. });
  87609. };
  87610. for (var buf in gltfRuntime.buffers) {
  87611. hasBuffers = true;
  87612. var buffer = gltfRuntime.buffers[buf];
  87613. if (buffer) {
  87614. processBuffer.bind(this, buf, buffer)();
  87615. }
  87616. else {
  87617. BABYLON.Tools.Error("No buffer named: " + buf);
  87618. }
  87619. }
  87620. if (!hasBuffers) {
  87621. onLoad();
  87622. }
  87623. };
  87624. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  87625. var currentScene = gltfRuntime.currentScene;
  87626. if (currentScene) {
  87627. // Only one scene even if multiple scenes are defined
  87628. for (var i = 0; i < currentScene.nodes.length; i++) {
  87629. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87630. }
  87631. }
  87632. else {
  87633. // Load all scenes
  87634. for (var thing in gltfRuntime.scenes) {
  87635. currentScene = gltfRuntime.scenes[thing];
  87636. for (var i = 0; i < currentScene.nodes.length; i++) {
  87637. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87638. }
  87639. }
  87640. }
  87641. };
  87642. GLTFLoader.Extensions = {};
  87643. return GLTFLoader;
  87644. }());
  87645. GLTF1.GLTFLoader = GLTFLoader;
  87646. ;
  87647. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  87648. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87649. })(BABYLON || (BABYLON = {}));
  87650. //# sourceMappingURL=babylon.glTFLoader.js.map
  87651. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87652. var BABYLON;
  87653. (function (BABYLON) {
  87654. var GLTF1;
  87655. (function (GLTF1) {
  87656. /**
  87657. * Utils functions for GLTF
  87658. */
  87659. var GLTFUtils = /** @class */ (function () {
  87660. function GLTFUtils() {
  87661. }
  87662. /**
  87663. * Sets the given "parameter" matrix
  87664. * @param scene: the {BABYLON.Scene} object
  87665. * @param source: the source node where to pick the matrix
  87666. * @param parameter: the GLTF technique parameter
  87667. * @param uniformName: the name of the shader's uniform
  87668. * @param shaderMaterial: the shader material
  87669. */
  87670. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  87671. var mat = null;
  87672. if (parameter.semantic === "MODEL") {
  87673. mat = source.getWorldMatrix();
  87674. }
  87675. else if (parameter.semantic === "PROJECTION") {
  87676. mat = scene.getProjectionMatrix();
  87677. }
  87678. else if (parameter.semantic === "VIEW") {
  87679. mat = scene.getViewMatrix();
  87680. }
  87681. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  87682. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  87683. }
  87684. else if (parameter.semantic === "MODELVIEW") {
  87685. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  87686. }
  87687. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  87688. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  87689. }
  87690. else if (parameter.semantic === "MODELINVERSE") {
  87691. mat = source.getWorldMatrix().invert();
  87692. }
  87693. else if (parameter.semantic === "VIEWINVERSE") {
  87694. mat = scene.getViewMatrix().invert();
  87695. }
  87696. else if (parameter.semantic === "PROJECTIONINVERSE") {
  87697. mat = scene.getProjectionMatrix().invert();
  87698. }
  87699. else if (parameter.semantic === "MODELVIEWINVERSE") {
  87700. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  87701. }
  87702. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  87703. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  87704. }
  87705. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  87706. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  87707. }
  87708. else {
  87709. debugger;
  87710. }
  87711. if (mat) {
  87712. switch (parameter.type) {
  87713. case GLTF1.EParameterType.FLOAT_MAT2:
  87714. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  87715. break;
  87716. case GLTF1.EParameterType.FLOAT_MAT3:
  87717. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  87718. break;
  87719. case GLTF1.EParameterType.FLOAT_MAT4:
  87720. shaderMaterial.setMatrix(uniformName, mat);
  87721. break;
  87722. default: break;
  87723. }
  87724. }
  87725. };
  87726. /**
  87727. * Sets the given "parameter" matrix
  87728. * @param shaderMaterial: the shader material
  87729. * @param uniform: the name of the shader's uniform
  87730. * @param value: the value of the uniform
  87731. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  87732. */
  87733. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  87734. switch (type) {
  87735. case GLTF1.EParameterType.FLOAT:
  87736. shaderMaterial.setFloat(uniform, value);
  87737. return true;
  87738. case GLTF1.EParameterType.FLOAT_VEC2:
  87739. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  87740. return true;
  87741. case GLTF1.EParameterType.FLOAT_VEC3:
  87742. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  87743. return true;
  87744. case GLTF1.EParameterType.FLOAT_VEC4:
  87745. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  87746. return true;
  87747. default: return false;
  87748. }
  87749. };
  87750. /**
  87751. * If the uri is a base64 string
  87752. * @param uri: the uri to test
  87753. */
  87754. GLTFUtils.IsBase64 = function (uri) {
  87755. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  87756. };
  87757. /**
  87758. * Decode the base64 uri
  87759. * @param uri: the uri to decode
  87760. */
  87761. GLTFUtils.DecodeBase64 = function (uri) {
  87762. var decodedString = atob(uri.split(",")[1]);
  87763. var bufferLength = decodedString.length;
  87764. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  87765. for (var i = 0; i < bufferLength; i++) {
  87766. bufferView[i] = decodedString.charCodeAt(i);
  87767. }
  87768. return bufferView.buffer;
  87769. };
  87770. /**
  87771. * Returns the wrap mode of the texture
  87772. * @param mode: the mode value
  87773. */
  87774. GLTFUtils.GetWrapMode = function (mode) {
  87775. switch (mode) {
  87776. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87777. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87778. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87779. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87780. }
  87781. };
  87782. /**
  87783. * Returns the byte stride giving an accessor
  87784. * @param accessor: the GLTF accessor objet
  87785. */
  87786. GLTFUtils.GetByteStrideFromType = function (accessor) {
  87787. // Needs this function since "byteStride" isn't requiered in glTF format
  87788. var type = accessor.type;
  87789. switch (type) {
  87790. case "VEC2": return 2;
  87791. case "VEC3": return 3;
  87792. case "VEC4": return 4;
  87793. case "MAT2": return 4;
  87794. case "MAT3": return 9;
  87795. case "MAT4": return 16;
  87796. default: return 1;
  87797. }
  87798. };
  87799. /**
  87800. * Returns the texture filter mode giving a mode value
  87801. * @param mode: the filter mode value
  87802. */
  87803. GLTFUtils.GetTextureFilterMode = function (mode) {
  87804. switch (mode) {
  87805. case GLTF1.ETextureFilterType.LINEAR:
  87806. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  87807. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87808. case GLTF1.ETextureFilterType.NEAREST:
  87809. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  87810. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87811. }
  87812. };
  87813. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  87814. var byteOffset = bufferView.byteOffset + byteOffset;
  87815. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  87816. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  87817. throw new Error("Buffer access is out of range");
  87818. }
  87819. var buffer = loadedBufferView.buffer;
  87820. byteOffset += loadedBufferView.byteOffset;
  87821. switch (componentType) {
  87822. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  87823. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  87824. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  87825. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  87826. default: return new Float32Array(buffer, byteOffset, byteLength);
  87827. }
  87828. };
  87829. /**
  87830. * Returns a buffer from its accessor
  87831. * @param gltfRuntime: the GLTF runtime
  87832. * @param accessor: the GLTF accessor
  87833. */
  87834. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  87835. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  87836. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  87837. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  87838. };
  87839. /**
  87840. * Decodes a buffer view into a string
  87841. * @param view: the buffer view
  87842. */
  87843. GLTFUtils.DecodeBufferToText = function (view) {
  87844. var result = "";
  87845. var length = view.byteLength;
  87846. for (var i = 0; i < length; ++i) {
  87847. result += String.fromCharCode(view[i]);
  87848. }
  87849. return result;
  87850. };
  87851. /**
  87852. * Returns the default material of gltf. Related to
  87853. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  87854. * @param scene: the Babylon.js scene
  87855. */
  87856. GLTFUtils.GetDefaultMaterial = function (scene) {
  87857. if (!GLTFUtils._DefaultMaterial) {
  87858. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  87859. "precision highp float;",
  87860. "",
  87861. "uniform mat4 worldView;",
  87862. "uniform mat4 projection;",
  87863. "",
  87864. "attribute vec3 position;",
  87865. "",
  87866. "void main(void)",
  87867. "{",
  87868. " gl_Position = projection * worldView * vec4(position, 1.0);",
  87869. "}"
  87870. ].join("\n");
  87871. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  87872. "precision highp float;",
  87873. "",
  87874. "uniform vec4 u_emission;",
  87875. "",
  87876. "void main(void)",
  87877. "{",
  87878. " gl_FragColor = u_emission;",
  87879. "}"
  87880. ].join("\n");
  87881. var shaderPath = {
  87882. vertex: "GLTFDefaultMaterial",
  87883. fragment: "GLTFDefaultMaterial"
  87884. };
  87885. var options = {
  87886. attributes: ["position"],
  87887. uniforms: ["worldView", "projection", "u_emission"],
  87888. samplers: new Array(),
  87889. needAlphaBlending: false
  87890. };
  87891. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  87892. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  87893. }
  87894. return GLTFUtils._DefaultMaterial;
  87895. };
  87896. // The GLTF default material
  87897. GLTFUtils._DefaultMaterial = null;
  87898. return GLTFUtils;
  87899. }());
  87900. GLTF1.GLTFUtils = GLTFUtils;
  87901. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87902. })(BABYLON || (BABYLON = {}));
  87903. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  87904. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87905. var BABYLON;
  87906. (function (BABYLON) {
  87907. var GLTF1;
  87908. (function (GLTF1) {
  87909. var GLTFLoaderExtension = /** @class */ (function () {
  87910. function GLTFLoaderExtension(name) {
  87911. this._name = name;
  87912. }
  87913. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  87914. get: function () {
  87915. return this._name;
  87916. },
  87917. enumerable: true,
  87918. configurable: true
  87919. });
  87920. /**
  87921. * Defines an override for loading the runtime
  87922. * Return true to stop further extensions from loading the runtime
  87923. */
  87924. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87925. return false;
  87926. };
  87927. /**
  87928. * Defines an onverride for creating gltf runtime
  87929. * Return true to stop further extensions from creating the runtime
  87930. */
  87931. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87932. return false;
  87933. };
  87934. /**
  87935. * Defines an override for loading buffers
  87936. * Return true to stop further extensions from loading this buffer
  87937. */
  87938. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87939. return false;
  87940. };
  87941. /**
  87942. * Defines an override for loading texture buffers
  87943. * Return true to stop further extensions from loading this texture data
  87944. */
  87945. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87946. return false;
  87947. };
  87948. /**
  87949. * Defines an override for creating textures
  87950. * Return true to stop further extensions from loading this texture
  87951. */
  87952. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87953. return false;
  87954. };
  87955. /**
  87956. * Defines an override for loading shader strings
  87957. * Return true to stop further extensions from loading this shader data
  87958. */
  87959. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87960. return false;
  87961. };
  87962. /**
  87963. * Defines an override for loading materials
  87964. * Return true to stop further extensions from loading this material
  87965. */
  87966. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87967. return false;
  87968. };
  87969. // ---------
  87970. // Utilities
  87971. // ---------
  87972. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87973. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87974. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  87975. }, function () {
  87976. setTimeout(function () {
  87977. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87978. });
  87979. });
  87980. };
  87981. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87982. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87983. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  87984. }, function () {
  87985. setTimeout(function () {
  87986. onSuccess();
  87987. });
  87988. });
  87989. };
  87990. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87991. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87992. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87993. }, function () {
  87994. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87995. });
  87996. };
  87997. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  87998. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  87999. };
  88000. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  88001. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  88002. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  88003. }, function () {
  88004. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  88005. });
  88006. };
  88007. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  88008. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  88009. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  88010. }, function () {
  88011. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  88012. });
  88013. };
  88014. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88015. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  88016. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  88017. }, function () {
  88018. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  88019. });
  88020. };
  88021. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  88022. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  88023. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  88024. }, function () {
  88025. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  88026. });
  88027. };
  88028. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  88029. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  88030. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  88031. if (func(loaderExtension)) {
  88032. return;
  88033. }
  88034. }
  88035. defaultFunc();
  88036. };
  88037. return GLTFLoaderExtension;
  88038. }());
  88039. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  88040. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88041. })(BABYLON || (BABYLON = {}));
  88042. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  88043. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88044. var BABYLON;
  88045. (function (BABYLON) {
  88046. var GLTF1;
  88047. (function (GLTF1) {
  88048. var BinaryExtensionBufferName = "binary_glTF";
  88049. ;
  88050. ;
  88051. var GLTFBinaryExtension = /** @class */ (function (_super) {
  88052. __extends(GLTFBinaryExtension, _super);
  88053. function GLTFBinaryExtension() {
  88054. return _super.call(this, "KHR_binary_glTF") || this;
  88055. }
  88056. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  88057. var extensionsUsed = data.json.extensionsUsed;
  88058. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  88059. return false;
  88060. }
  88061. this._bin = data.bin;
  88062. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  88063. return true;
  88064. };
  88065. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88066. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  88067. return false;
  88068. }
  88069. if (id !== BinaryExtensionBufferName) {
  88070. return false;
  88071. }
  88072. onSuccess(this._bin);
  88073. return true;
  88074. };
  88075. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88076. var texture = gltfRuntime.textures[id];
  88077. var source = gltfRuntime.images[texture.source];
  88078. if (!source.extensions || !(this.name in source.extensions)) {
  88079. return false;
  88080. }
  88081. var sourceExt = source.extensions[this.name];
  88082. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  88083. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  88084. onSuccess(buffer);
  88085. return true;
  88086. };
  88087. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  88088. var shader = gltfRuntime.shaders[id];
  88089. if (!shader.extensions || !(this.name in shader.extensions)) {
  88090. return false;
  88091. }
  88092. var binaryExtensionShader = shader.extensions[this.name];
  88093. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  88094. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  88095. setTimeout(function () {
  88096. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  88097. onSuccess(shaderString);
  88098. });
  88099. return true;
  88100. };
  88101. return GLTFBinaryExtension;
  88102. }(GLTF1.GLTFLoaderExtension));
  88103. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  88104. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  88105. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88106. })(BABYLON || (BABYLON = {}));
  88107. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  88108. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88109. var BABYLON;
  88110. (function (BABYLON) {
  88111. var GLTF1;
  88112. (function (GLTF1) {
  88113. ;
  88114. ;
  88115. ;
  88116. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  88117. __extends(GLTFMaterialsCommonExtension, _super);
  88118. function GLTFMaterialsCommonExtension() {
  88119. return _super.call(this, "KHR_materials_common") || this;
  88120. }
  88121. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  88122. if (!gltfRuntime.extensions)
  88123. return false;
  88124. var extension = gltfRuntime.extensions[this.name];
  88125. if (!extension)
  88126. return false;
  88127. // Create lights
  88128. var lights = extension.lights;
  88129. if (lights) {
  88130. for (var thing in lights) {
  88131. var light = lights[thing];
  88132. switch (light.type) {
  88133. case "ambient":
  88134. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  88135. var ambient = light.ambient;
  88136. if (ambient) {
  88137. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  88138. }
  88139. break;
  88140. case "point":
  88141. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  88142. var point = light.point;
  88143. if (point) {
  88144. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  88145. }
  88146. break;
  88147. case "directional":
  88148. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  88149. var directional = light.directional;
  88150. if (directional) {
  88151. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  88152. }
  88153. break;
  88154. case "spot":
  88155. var spot = light.spot;
  88156. if (spot) {
  88157. 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);
  88158. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  88159. }
  88160. break;
  88161. default:
  88162. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  88163. break;
  88164. }
  88165. }
  88166. }
  88167. return false;
  88168. };
  88169. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  88170. var material = gltfRuntime.materials[id];
  88171. if (!material || !material.extensions)
  88172. return false;
  88173. var extension = material.extensions[this.name];
  88174. if (!extension)
  88175. return false;
  88176. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  88177. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  88178. if (extension.technique === "CONSTANT") {
  88179. standardMaterial.disableLighting = true;
  88180. }
  88181. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  88182. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  88183. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  88184. // Ambient
  88185. if (typeof extension.values.ambient === "string") {
  88186. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  88187. }
  88188. else {
  88189. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  88190. }
  88191. // Diffuse
  88192. if (typeof extension.values.diffuse === "string") {
  88193. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  88194. }
  88195. else {
  88196. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  88197. }
  88198. // Emission
  88199. if (typeof extension.values.emission === "string") {
  88200. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  88201. }
  88202. else {
  88203. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  88204. }
  88205. // Specular
  88206. if (typeof extension.values.specular === "string") {
  88207. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  88208. }
  88209. else {
  88210. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  88211. }
  88212. return true;
  88213. };
  88214. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  88215. // Create buffer from texture url
  88216. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  88217. // Create texture from buffer
  88218. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  88219. }, onError);
  88220. };
  88221. return GLTFMaterialsCommonExtension;
  88222. }(GLTF1.GLTFLoaderExtension));
  88223. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  88224. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  88225. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88226. })(BABYLON || (BABYLON = {}));
  88227. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  88228. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88229. var BABYLON;
  88230. (function (BABYLON) {
  88231. var GLTF2;
  88232. (function (GLTF2) {
  88233. /**
  88234. * Enums
  88235. */
  88236. var EComponentType;
  88237. (function (EComponentType) {
  88238. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88239. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88240. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88241. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88242. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88243. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88244. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  88245. var EMeshPrimitiveMode;
  88246. (function (EMeshPrimitiveMode) {
  88247. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  88248. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  88249. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  88250. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  88251. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  88252. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  88253. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  88254. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  88255. var ETextureMagFilter;
  88256. (function (ETextureMagFilter) {
  88257. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  88258. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  88259. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  88260. var ETextureMinFilter;
  88261. (function (ETextureMinFilter) {
  88262. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  88263. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  88264. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88265. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88266. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88267. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88268. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  88269. var ETextureWrapMode;
  88270. (function (ETextureWrapMode) {
  88271. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88272. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88273. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88274. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  88275. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88276. })(BABYLON || (BABYLON = {}));
  88277. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88278. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88279. var BABYLON;
  88280. (function (BABYLON) {
  88281. var GLTF2;
  88282. (function (GLTF2) {
  88283. var GLTFLoaderTracker = /** @class */ (function () {
  88284. function GLTFLoaderTracker(onComplete) {
  88285. this._pendingCount = 0;
  88286. this._callback = onComplete;
  88287. }
  88288. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  88289. this._pendingCount++;
  88290. };
  88291. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  88292. if (--this._pendingCount === 0) {
  88293. this._callback();
  88294. }
  88295. };
  88296. return GLTFLoaderTracker;
  88297. }());
  88298. var GLTFLoader = /** @class */ (function () {
  88299. function GLTFLoader() {
  88300. this._disposed = false;
  88301. this._defaultSampler = {};
  88302. this._renderReady = false;
  88303. this._requests = new Array();
  88304. this._renderReadyObservable = new BABYLON.Observable();
  88305. // Count of pending work that needs to complete before the asset is rendered.
  88306. this._renderPendingCount = 0;
  88307. // Count of pending work that needs to complete before the loader is disposed.
  88308. this._loaderPendingCount = 0;
  88309. this._loaderTrackers = new Array();
  88310. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  88311. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  88312. this.compileMaterials = false;
  88313. this.useClipPlane = false;
  88314. this.compileShadowGenerators = false;
  88315. this.onDisposeObservable = new BABYLON.Observable();
  88316. this.onMeshLoadedObservable = new BABYLON.Observable();
  88317. this.onTextureLoadedObservable = new BABYLON.Observable();
  88318. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88319. this.onCompleteObservable = new BABYLON.Observable();
  88320. }
  88321. GLTFLoader.RegisterExtension = function (extension) {
  88322. if (GLTFLoader.Extensions[extension.name]) {
  88323. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  88324. return;
  88325. }
  88326. GLTFLoader.Extensions[extension.name] = extension;
  88327. // Keep the order of registration so that extensions registered first are called first.
  88328. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  88329. };
  88330. GLTFLoader.prototype.dispose = function () {
  88331. if (this._disposed) {
  88332. return;
  88333. }
  88334. this._disposed = true;
  88335. this._abortRequests();
  88336. this._releaseResources();
  88337. this.onDisposeObservable.notifyObservers(this);
  88338. };
  88339. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  88340. var _this = this;
  88341. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  88342. if (onSuccess) {
  88343. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  88344. }
  88345. }, onProgress, onError);
  88346. };
  88347. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  88348. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  88349. };
  88350. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  88351. var _this = this;
  88352. this._babylonScene = scene;
  88353. this._rootUrl = rootUrl;
  88354. this._successCallback = onSuccess;
  88355. this._progressCallback = onProgress;
  88356. this._errorCallback = onError;
  88357. this._tryCatchOnError(function () {
  88358. _this._loadData(data);
  88359. _this._addPendingData(_this);
  88360. _this._loadDefaultScene(nodeNames);
  88361. _this._loadAnimations();
  88362. _this._removePendingData(_this);
  88363. });
  88364. };
  88365. GLTFLoader.prototype._onProgress = function () {
  88366. if (!this._progressCallback) {
  88367. return;
  88368. }
  88369. var lengthComputable = true;
  88370. var loaded = 0;
  88371. var total = 0;
  88372. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  88373. var request = _a[_i];
  88374. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  88375. return;
  88376. }
  88377. lengthComputable = lengthComputable && request._lengthComputable;
  88378. loaded += request._loaded;
  88379. total += request._total;
  88380. }
  88381. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  88382. };
  88383. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  88384. if (this._renderReady) {
  88385. func();
  88386. }
  88387. else {
  88388. this._renderReadyObservable.add(func);
  88389. }
  88390. };
  88391. GLTFLoader.prototype._onRenderReady = function () {
  88392. this._rootNode.babylonMesh.setEnabled(true);
  88393. this._startAnimations();
  88394. if (this._successCallback) {
  88395. this._successCallback();
  88396. }
  88397. this._renderReadyObservable.notifyObservers(this);
  88398. };
  88399. GLTFLoader.prototype._onComplete = function () {
  88400. this._abortRequests();
  88401. this._releaseResources();
  88402. this.onCompleteObservable.notifyObservers(this);
  88403. };
  88404. GLTFLoader.prototype._loadData = function (data) {
  88405. this._gltf = data.json;
  88406. // Assign the index of each object for convinience.
  88407. GLTFLoader._AssignIndices(this._gltf.accessors);
  88408. GLTFLoader._AssignIndices(this._gltf.animations);
  88409. GLTFLoader._AssignIndices(this._gltf.buffers);
  88410. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  88411. GLTFLoader._AssignIndices(this._gltf.images);
  88412. GLTFLoader._AssignIndices(this._gltf.materials);
  88413. GLTFLoader._AssignIndices(this._gltf.meshes);
  88414. GLTFLoader._AssignIndices(this._gltf.nodes);
  88415. GLTFLoader._AssignIndices(this._gltf.samplers);
  88416. GLTFLoader._AssignIndices(this._gltf.scenes);
  88417. GLTFLoader._AssignIndices(this._gltf.skins);
  88418. GLTFLoader._AssignIndices(this._gltf.textures);
  88419. // Handle global extensions as they may add their own data types.
  88420. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  88421. if (data.bin) {
  88422. var buffers = this._gltf.buffers;
  88423. if (buffers && buffers[0] && !buffers[0].uri) {
  88424. var binaryBuffer = buffers[0];
  88425. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  88426. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  88427. }
  88428. binaryBuffer.loadedData = data.bin;
  88429. }
  88430. else {
  88431. BABYLON.Tools.Warn("Unexpected BIN chunk");
  88432. }
  88433. }
  88434. };
  88435. GLTFLoader.prototype._getMeshes = function () {
  88436. var meshes = new Array();
  88437. // Root mesh is always first.
  88438. meshes.push(this._rootNode.babylonMesh);
  88439. var nodes = this._gltf.nodes;
  88440. if (nodes) {
  88441. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  88442. var node = nodes_1[_i];
  88443. if (node.babylonMesh) {
  88444. meshes.push(node.babylonMesh);
  88445. }
  88446. }
  88447. }
  88448. return meshes;
  88449. };
  88450. GLTFLoader.prototype._getSkeletons = function () {
  88451. var skeletons = new Array();
  88452. var skins = this._gltf.skins;
  88453. if (skins) {
  88454. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  88455. var skin = skins_1[_i];
  88456. if (skin.babylonSkeleton) {
  88457. skeletons.push(skin.babylonSkeleton);
  88458. }
  88459. }
  88460. }
  88461. return skeletons;
  88462. };
  88463. GLTFLoader.prototype._startAnimations = function () {
  88464. var animations = this._gltf.animations;
  88465. if (!animations) {
  88466. return;
  88467. }
  88468. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  88469. var animation = animations_1[_i];
  88470. animation.babylonAnimationGroup.normalize();
  88471. }
  88472. switch (this.animationStartMode) {
  88473. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  88474. // do nothing
  88475. break;
  88476. }
  88477. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  88478. var animation = animations[0];
  88479. animation.babylonAnimationGroup.start(true);
  88480. break;
  88481. }
  88482. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  88483. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  88484. var animation = animations_2[_a];
  88485. animation.babylonAnimationGroup.start(true);
  88486. }
  88487. break;
  88488. }
  88489. default: {
  88490. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  88491. return;
  88492. }
  88493. }
  88494. };
  88495. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  88496. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  88497. if (!scene) {
  88498. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  88499. }
  88500. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  88501. };
  88502. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  88503. var _this = this;
  88504. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  88505. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  88506. switch (this.coordinateSystemMode) {
  88507. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  88508. if (!this._babylonScene.useRightHandedSystem) {
  88509. this._rootNode.rotation = [0, 1, 0, 0];
  88510. this._rootNode.scale = [1, 1, -1];
  88511. this._loadTransform(this._rootNode);
  88512. }
  88513. break;
  88514. }
  88515. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  88516. this._babylonScene.useRightHandedSystem = true;
  88517. break;
  88518. }
  88519. default: {
  88520. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  88521. return;
  88522. }
  88523. }
  88524. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  88525. var nodeIndices = scene.nodes;
  88526. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  88527. node.parent = parentNode;
  88528. return true;
  88529. }, this._rootNode);
  88530. if (nodeNames) {
  88531. if (!(nodeNames instanceof Array)) {
  88532. nodeNames = [nodeNames];
  88533. }
  88534. var filteredNodeIndices_1 = new Array();
  88535. this._traverseNodes(context, nodeIndices, function (node) {
  88536. if (nodeNames.indexOf(node.name) !== -1) {
  88537. filteredNodeIndices_1.push(node.index);
  88538. node.parent = _this._rootNode;
  88539. return false;
  88540. }
  88541. return true;
  88542. }, this._rootNode);
  88543. nodeIndices = filteredNodeIndices_1;
  88544. }
  88545. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  88546. var index = nodeIndices_1[_i];
  88547. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88548. if (!node) {
  88549. throw new Error(context + ": Failed to find node " + index);
  88550. }
  88551. this._loadNode("#/nodes/" + index, node);
  88552. }
  88553. // Disable the root mesh until the asset is ready to render.
  88554. this._rootNode.babylonMesh.setEnabled(false);
  88555. };
  88556. GLTFLoader.prototype._loadNode = function (context, node) {
  88557. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  88558. return;
  88559. }
  88560. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  88561. this._loadTransform(node);
  88562. if (node.mesh != null) {
  88563. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  88564. if (!mesh) {
  88565. throw new Error(context + ": Failed to find mesh " + node.mesh);
  88566. }
  88567. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  88568. }
  88569. node.babylonMesh.parent = node.parent.babylonMesh;
  88570. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88571. node.babylonAnimationTargets.push(node.babylonMesh);
  88572. if (node.skin != null) {
  88573. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  88574. if (!skin_1) {
  88575. throw new Error(context + ": Failed to find skin " + node.skin);
  88576. }
  88577. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  88578. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  88579. node.babylonMesh._refreshBoundingInfo(true);
  88580. });
  88581. node.babylonMesh.parent = this._rootNode.babylonMesh;
  88582. node.babylonMesh.position = BABYLON.Vector3.Zero();
  88583. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88584. node.babylonMesh.scaling = BABYLON.Vector3.One();
  88585. }
  88586. if (node.camera != null) {
  88587. // TODO: handle cameras
  88588. }
  88589. if (node.children) {
  88590. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  88591. var index = _a[_i];
  88592. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88593. if (!childNode) {
  88594. throw new Error(context + ": Failed to find child node " + index);
  88595. }
  88596. this._loadNode("#/nodes/" + index, childNode);
  88597. }
  88598. }
  88599. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  88600. };
  88601. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  88602. var _this = this;
  88603. var primitives = mesh.primitives;
  88604. if (!primitives || primitives.length === 0) {
  88605. throw new Error(context + ": Primitives are missing");
  88606. }
  88607. this._createMorphTargets(context, node, mesh);
  88608. this._loadAllVertexDataAsync(context, mesh, function () {
  88609. _this._loadMorphTargets(context, node, mesh);
  88610. var vertexData = new BABYLON.VertexData();
  88611. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  88612. var primitive = primitives_1[_i];
  88613. vertexData.merge(primitive.vertexData);
  88614. }
  88615. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  88616. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  88617. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  88618. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  88619. node.babylonMesh.subMeshes = [];
  88620. var verticesStart = 0;
  88621. var indicesStart = 0;
  88622. for (var index = 0; index < primitives.length; index++) {
  88623. var vertexData_1 = primitives[index].vertexData;
  88624. var verticesCount = vertexData_1.positions.length;
  88625. var indicesCount = vertexData_1.indices.length;
  88626. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  88627. verticesStart += verticesCount;
  88628. indicesStart += indicesCount;
  88629. }
  88630. ;
  88631. });
  88632. if (primitives.length === 1) {
  88633. var primitive = primitives[0];
  88634. if (primitive.material == null) {
  88635. node.babylonMesh.material = this._getDefaultMaterial();
  88636. }
  88637. else {
  88638. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  88639. if (!material) {
  88640. throw new Error(context + ": Failed to find material " + primitive.material);
  88641. }
  88642. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88643. if (isNew) {
  88644. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88645. }
  88646. node.babylonMesh.material = babylonMaterial;
  88647. });
  88648. }
  88649. }
  88650. else {
  88651. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  88652. node.babylonMesh.material = multiMaterial;
  88653. var subMaterials_1 = multiMaterial.subMaterials;
  88654. var _loop_1 = function (index) {
  88655. var primitive = primitives[index];
  88656. if (primitive.material == null) {
  88657. subMaterials_1[index] = this_1._getDefaultMaterial();
  88658. }
  88659. else {
  88660. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  88661. if (!material) {
  88662. throw new Error(context + ": Failed to find material " + primitive.material);
  88663. }
  88664. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88665. if (isNew) {
  88666. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88667. }
  88668. subMaterials_1[index] = babylonMaterial;
  88669. });
  88670. }
  88671. };
  88672. var this_1 = this;
  88673. for (var index = 0; index < primitives.length; index++) {
  88674. _loop_1(index);
  88675. }
  88676. ;
  88677. }
  88678. };
  88679. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  88680. var primitives = mesh.primitives;
  88681. var numRemainingPrimitives = primitives.length;
  88682. var _loop_2 = function (index) {
  88683. var primitive = primitives[index];
  88684. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  88685. primitive.vertexData = vertexData;
  88686. if (--numRemainingPrimitives === 0) {
  88687. onSuccess();
  88688. }
  88689. });
  88690. };
  88691. var this_2 = this;
  88692. for (var index = 0; index < primitives.length; index++) {
  88693. _loop_2(index);
  88694. }
  88695. };
  88696. /**
  88697. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  88698. * @param {ArrayBufferView} data
  88699. * @param {IGLTFAccessor} accessor
  88700. */
  88701. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  88702. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  88703. return data;
  88704. }
  88705. var buffer = data;
  88706. var factor = 1;
  88707. switch (accessor.componentType) {
  88708. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88709. factor = 1 / 255;
  88710. break;
  88711. }
  88712. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88713. factor = 1 / 65535;
  88714. break;
  88715. }
  88716. default: {
  88717. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88718. }
  88719. }
  88720. var result = new Float32Array(accessor.count * 2);
  88721. for (var i = 0; i < result.length; ++i) {
  88722. result[i] = buffer[i] * factor;
  88723. }
  88724. return result;
  88725. };
  88726. /**
  88727. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  88728. * @param {ArrayBufferView} data
  88729. * @param {IGLTFAccessor} accessor
  88730. */
  88731. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  88732. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  88733. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  88734. return data;
  88735. }
  88736. var buffer = data;
  88737. var factor = 1;
  88738. switch (accessor.componentType) {
  88739. case GLTF2.EComponentType.FLOAT: {
  88740. factor = 1;
  88741. break;
  88742. }
  88743. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88744. factor = 1 / 255;
  88745. break;
  88746. }
  88747. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88748. factor = 1 / 65535;
  88749. break;
  88750. }
  88751. default: {
  88752. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88753. }
  88754. }
  88755. var result = new Float32Array(accessor.count * 4);
  88756. if (colorComponentCount === 4) {
  88757. for (var i = 0; i < result.length; ++i) {
  88758. result[i] = buffer[i] * factor;
  88759. }
  88760. }
  88761. else {
  88762. var offset = 0;
  88763. for (var i = 0; i < result.length; ++i) {
  88764. if ((i + 1) % 4 === 0) {
  88765. result[i] = 1;
  88766. }
  88767. else {
  88768. result[i] = buffer[offset++] * factor;
  88769. }
  88770. }
  88771. }
  88772. return result;
  88773. };
  88774. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  88775. var _this = this;
  88776. var attributes = primitive.attributes;
  88777. if (!attributes) {
  88778. throw new Error(context + ": Attributes are missing");
  88779. }
  88780. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  88781. // TODO: handle other primitive modes
  88782. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  88783. }
  88784. var vertexData = new BABYLON.VertexData();
  88785. var numRemainingAttributes = Object.keys(attributes).length;
  88786. var _loop_3 = function (attribute) {
  88787. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  88788. if (!accessor) {
  88789. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88790. }
  88791. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88792. switch (attribute) {
  88793. case "POSITION": {
  88794. vertexData.positions = data;
  88795. break;
  88796. }
  88797. case "NORMAL": {
  88798. vertexData.normals = data;
  88799. break;
  88800. }
  88801. case "TANGENT": {
  88802. vertexData.tangents = data;
  88803. break;
  88804. }
  88805. case "TEXCOORD_0": {
  88806. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88807. break;
  88808. }
  88809. case "TEXCOORD_1": {
  88810. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88811. break;
  88812. }
  88813. case "JOINTS_0": {
  88814. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  88815. break;
  88816. }
  88817. case "WEIGHTS_0": {
  88818. //TODO: need to add support for normalized weights.
  88819. vertexData.matricesWeights = data;
  88820. break;
  88821. }
  88822. case "COLOR_0": {
  88823. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  88824. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  88825. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  88826. mesh.hasVertexAlpha = hasVertexAlpha;
  88827. }
  88828. break;
  88829. }
  88830. default: {
  88831. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88832. break;
  88833. }
  88834. }
  88835. if (--numRemainingAttributes === 0) {
  88836. if (primitive.indices == null) {
  88837. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  88838. for (var i = 0; i < vertexData.indices.length; i++) {
  88839. vertexData.indices[i] = i;
  88840. }
  88841. onSuccess(vertexData);
  88842. }
  88843. else {
  88844. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  88845. if (!indicesAccessor) {
  88846. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  88847. }
  88848. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  88849. vertexData.indices = data;
  88850. onSuccess(vertexData);
  88851. });
  88852. }
  88853. }
  88854. });
  88855. };
  88856. var this_3 = this;
  88857. for (var attribute in attributes) {
  88858. _loop_3(attribute);
  88859. }
  88860. };
  88861. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  88862. var primitives = mesh.primitives;
  88863. var targets = primitives[0].targets;
  88864. if (!targets) {
  88865. return;
  88866. }
  88867. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  88868. var primitive = primitives_2[_i];
  88869. if (!primitive.targets || primitive.targets.length != targets.length) {
  88870. throw new Error(context + ": All primitives are required to list the same number of targets");
  88871. }
  88872. }
  88873. var morphTargetManager = new BABYLON.MorphTargetManager();
  88874. node.babylonMesh.morphTargetManager = morphTargetManager;
  88875. for (var index = 0; index < targets.length; index++) {
  88876. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  88877. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  88878. }
  88879. };
  88880. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  88881. var morphTargetManager = node.babylonMesh.morphTargetManager;
  88882. if (!morphTargetManager) {
  88883. return;
  88884. }
  88885. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  88886. var numTargets = morphTargetManager.numTargets;
  88887. for (var index = 0; index < numTargets; index++) {
  88888. var vertexData = new BABYLON.VertexData();
  88889. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88890. var primitive = _a[_i];
  88891. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  88892. }
  88893. if (!vertexData.positions) {
  88894. throw new Error(context + ": Positions are missing");
  88895. }
  88896. var target = morphTargetManager.getTarget(index);
  88897. target.setPositions(vertexData.positions);
  88898. target.setNormals(vertexData.normals);
  88899. target.setTangents(vertexData.tangents);
  88900. }
  88901. });
  88902. };
  88903. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  88904. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  88905. var _loop_4 = function (primitive) {
  88906. var targets = primitive.targets;
  88907. primitive.targetsVertexData = new Array(targets.length);
  88908. var _loop_5 = function (index) {
  88909. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  88910. primitive.targetsVertexData[index] = vertexData;
  88911. if (--numRemainingTargets === 0) {
  88912. onSuccess();
  88913. }
  88914. });
  88915. };
  88916. for (var index = 0; index < targets.length; index++) {
  88917. _loop_5(index);
  88918. }
  88919. };
  88920. var this_4 = this;
  88921. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88922. var primitive = _a[_i];
  88923. _loop_4(primitive);
  88924. }
  88925. };
  88926. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  88927. var targetVertexData = new BABYLON.VertexData();
  88928. var numRemainingAttributes = Object.keys(attributes).length;
  88929. var _loop_6 = function (attribute) {
  88930. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  88931. if (!accessor) {
  88932. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88933. }
  88934. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88935. // glTF stores morph target information as deltas while babylon.js expects the final data.
  88936. // As a result we have to add the original data to the delta to calculate the final data.
  88937. var values = data;
  88938. switch (attribute) {
  88939. case "POSITION": {
  88940. for (var i = 0; i < values.length; i++) {
  88941. values[i] += vertexData.positions[i];
  88942. }
  88943. targetVertexData.positions = values;
  88944. break;
  88945. }
  88946. case "NORMAL": {
  88947. for (var i = 0; i < values.length; i++) {
  88948. values[i] += vertexData.normals[i];
  88949. }
  88950. targetVertexData.normals = values;
  88951. break;
  88952. }
  88953. case "TANGENT": {
  88954. // Tangent data for morph targets is stored as xyz delta.
  88955. // The vertexData.tangent is stored as xyzw.
  88956. // So we need to skip every fourth vertexData.tangent.
  88957. for (var i = 0, j = 0; i < values.length; i++, j++) {
  88958. values[i] += vertexData.tangents[j];
  88959. if ((i + 1) % 3 == 0) {
  88960. j++;
  88961. }
  88962. }
  88963. targetVertexData.tangents = values;
  88964. break;
  88965. }
  88966. default: {
  88967. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88968. break;
  88969. }
  88970. }
  88971. if (--numRemainingAttributes === 0) {
  88972. onSuccess(targetVertexData);
  88973. }
  88974. });
  88975. };
  88976. var this_5 = this;
  88977. for (var attribute in attributes) {
  88978. _loop_6(attribute);
  88979. }
  88980. };
  88981. GLTFLoader.prototype._loadTransform = function (node) {
  88982. var position = BABYLON.Vector3.Zero();
  88983. var rotation = BABYLON.Quaternion.Identity();
  88984. var scaling = BABYLON.Vector3.One();
  88985. if (node.matrix) {
  88986. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  88987. matrix.decompose(scaling, rotation, position);
  88988. }
  88989. else {
  88990. if (node.translation)
  88991. position = BABYLON.Vector3.FromArray(node.translation);
  88992. if (node.rotation)
  88993. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  88994. if (node.scale)
  88995. scaling = BABYLON.Vector3.FromArray(node.scale);
  88996. }
  88997. node.babylonMesh.position = position;
  88998. node.babylonMesh.rotationQuaternion = rotation;
  88999. node.babylonMesh.scaling = scaling;
  89000. };
  89001. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  89002. var _this = this;
  89003. if (skin.babylonSkeleton) {
  89004. onSuccess();
  89005. return;
  89006. }
  89007. var skeletonId = "skeleton" + skin.index;
  89008. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  89009. if (skin.inverseBindMatrices == null) {
  89010. this._loadBones(context, skin, null);
  89011. onSuccess();
  89012. }
  89013. else {
  89014. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  89015. if (!accessor) {
  89016. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  89017. }
  89018. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  89019. _this._loadBones(context, skin, data);
  89020. onSuccess();
  89021. });
  89022. }
  89023. };
  89024. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  89025. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  89026. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  89027. node.babylonAnimationTargets.push(babylonBone);
  89028. return babylonBone;
  89029. };
  89030. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  89031. var babylonBones = {};
  89032. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  89033. var index = _a[_i];
  89034. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89035. if (!node) {
  89036. throw new Error(context + ": Failed to find joint " + index);
  89037. }
  89038. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  89039. }
  89040. };
  89041. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  89042. var babylonBone = babylonBones[node.index];
  89043. if (babylonBone) {
  89044. return babylonBone;
  89045. }
  89046. var boneIndex = skin.joints.indexOf(node.index);
  89047. var baseMatrix = BABYLON.Matrix.Identity();
  89048. if (inverseBindMatrixData && boneIndex !== -1) {
  89049. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  89050. baseMatrix.invertToRef(baseMatrix);
  89051. }
  89052. var babylonParentBone = null;
  89053. if (node.parent !== this._rootNode) {
  89054. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  89055. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  89056. }
  89057. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  89058. babylonBones[node.index] = babylonBone;
  89059. return babylonBone;
  89060. };
  89061. GLTFLoader.prototype._getNodeMatrix = function (node) {
  89062. return node.matrix ?
  89063. BABYLON.Matrix.FromArray(node.matrix) :
  89064. 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());
  89065. };
  89066. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  89067. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  89068. var index = indices_1[_i];
  89069. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89070. if (!node) {
  89071. throw new Error(context + ": Failed to find node " + index);
  89072. }
  89073. this._traverseNode(context, node, action, parentNode);
  89074. }
  89075. };
  89076. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  89077. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  89078. return;
  89079. }
  89080. if (!action(node, parentNode)) {
  89081. return;
  89082. }
  89083. if (node.children) {
  89084. this._traverseNodes(context, node.children, action, node);
  89085. }
  89086. };
  89087. GLTFLoader.prototype._loadAnimations = function () {
  89088. var animations = this._gltf.animations;
  89089. if (!animations) {
  89090. return;
  89091. }
  89092. for (var index = 0; index < animations.length; index++) {
  89093. var animation = animations[index];
  89094. this._loadAnimation("#/animations/" + index, animation);
  89095. }
  89096. };
  89097. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  89098. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  89099. for (var index = 0; index < animation.channels.length; index++) {
  89100. var channel = GLTFLoader._GetProperty(animation.channels, index);
  89101. if (!channel) {
  89102. throw new Error(context + ": Failed to find channel " + index);
  89103. }
  89104. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  89105. if (!sampler) {
  89106. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  89107. }
  89108. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  89109. }
  89110. };
  89111. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  89112. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  89113. if (!targetNode) {
  89114. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  89115. }
  89116. var targetPath;
  89117. var animationType;
  89118. switch (channel.target.path) {
  89119. case "translation": {
  89120. targetPath = "position";
  89121. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89122. break;
  89123. }
  89124. case "rotation": {
  89125. targetPath = "rotationQuaternion";
  89126. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  89127. break;
  89128. }
  89129. case "scale": {
  89130. targetPath = "scaling";
  89131. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89132. break;
  89133. }
  89134. case "weights": {
  89135. targetPath = "influence";
  89136. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  89137. break;
  89138. }
  89139. default: {
  89140. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  89141. }
  89142. }
  89143. var inputData;
  89144. var outputData;
  89145. var checkSuccess = function () {
  89146. if (!inputData || !outputData) {
  89147. return;
  89148. }
  89149. var outputBufferOffset = 0;
  89150. var getNextOutputValue;
  89151. switch (targetPath) {
  89152. case "position": {
  89153. getNextOutputValue = function () {
  89154. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  89155. outputBufferOffset += 3;
  89156. return value;
  89157. };
  89158. break;
  89159. }
  89160. case "rotationQuaternion": {
  89161. getNextOutputValue = function () {
  89162. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  89163. outputBufferOffset += 4;
  89164. return value;
  89165. };
  89166. break;
  89167. }
  89168. case "scaling": {
  89169. getNextOutputValue = function () {
  89170. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  89171. outputBufferOffset += 3;
  89172. return value;
  89173. };
  89174. break;
  89175. }
  89176. case "influence": {
  89177. getNextOutputValue = function () {
  89178. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  89179. var value = new Array(numTargets);
  89180. for (var i = 0; i < numTargets; i++) {
  89181. value[i] = outputData[outputBufferOffset++];
  89182. }
  89183. return value;
  89184. };
  89185. break;
  89186. }
  89187. }
  89188. sampler.interpolation = sampler.interpolation || "LINEAR";
  89189. var getNextKey;
  89190. switch (sampler.interpolation) {
  89191. case "STEP": {
  89192. getNextKey = function (frameIndex) { return ({
  89193. frame: inputData[frameIndex],
  89194. value: getNextOutputValue(),
  89195. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  89196. }); };
  89197. break;
  89198. }
  89199. case "LINEAR": {
  89200. getNextKey = function (frameIndex) { return ({
  89201. frame: inputData[frameIndex],
  89202. value: getNextOutputValue()
  89203. }); };
  89204. break;
  89205. }
  89206. case "CUBICSPLINE": {
  89207. getNextKey = function (frameIndex) { return ({
  89208. frame: inputData[frameIndex],
  89209. inTangent: getNextOutputValue(),
  89210. value: getNextOutputValue(),
  89211. outTangent: getNextOutputValue()
  89212. }); };
  89213. break;
  89214. }
  89215. default: {
  89216. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  89217. }
  89218. }
  89219. ;
  89220. var keys;
  89221. if (inputData.length === 1) {
  89222. var key = getNextKey(0);
  89223. keys = [
  89224. { frame: key.frame, value: key.value },
  89225. { frame: key.frame + 1, value: key.value }
  89226. ];
  89227. }
  89228. else {
  89229. keys = new Array(inputData.length);
  89230. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  89231. keys[frameIndex] = getNextKey(frameIndex);
  89232. }
  89233. }
  89234. if (targetPath === "influence") {
  89235. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  89236. var _loop_7 = function (targetIndex) {
  89237. var morphTarget = morphTargetManager.getTarget(targetIndex);
  89238. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  89239. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  89240. babylonAnimation.setKeys(keys.map(function (key) { return ({
  89241. frame: key.frame,
  89242. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  89243. value: key.value[targetIndex],
  89244. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  89245. }); }));
  89246. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  89247. };
  89248. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  89249. _loop_7(targetIndex);
  89250. }
  89251. }
  89252. else {
  89253. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  89254. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  89255. babylonAnimation.setKeys(keys);
  89256. if (targetNode.babylonAnimationTargets) {
  89257. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  89258. var target = _a[_i];
  89259. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  89260. }
  89261. }
  89262. }
  89263. };
  89264. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  89265. if (!inputAccessor) {
  89266. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  89267. }
  89268. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  89269. inputData = data;
  89270. checkSuccess();
  89271. });
  89272. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  89273. if (!outputAccessor) {
  89274. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  89275. }
  89276. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  89277. outputData = data;
  89278. checkSuccess();
  89279. });
  89280. };
  89281. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  89282. var _this = this;
  89283. this._addPendingData(buffer);
  89284. if (buffer.loadedData) {
  89285. onSuccess(buffer.loadedData);
  89286. this._removePendingData(buffer);
  89287. }
  89288. else if (buffer.loadedObservable) {
  89289. buffer.loadedObservable.add(function (buffer) {
  89290. onSuccess(buffer.loadedData);
  89291. _this._removePendingData(buffer);
  89292. });
  89293. }
  89294. else {
  89295. if (!buffer.uri) {
  89296. throw new Error(context + ": Uri is missing");
  89297. }
  89298. buffer.loadedObservable = new BABYLON.Observable();
  89299. buffer.loadedObservable.add(function (buffer) {
  89300. onSuccess(buffer.loadedData);
  89301. _this._removePendingData(buffer);
  89302. });
  89303. this._loadUriAsync(context, buffer.uri, function (data) {
  89304. buffer.loadedData = data;
  89305. buffer.loadedObservable.notifyObservers(buffer);
  89306. buffer.loadedObservable = undefined;
  89307. });
  89308. }
  89309. };
  89310. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  89311. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  89312. if (!buffer) {
  89313. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  89314. }
  89315. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  89316. var data;
  89317. try {
  89318. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  89319. }
  89320. catch (e) {
  89321. throw new Error(context + ": " + e.message);
  89322. }
  89323. onSuccess(data);
  89324. });
  89325. };
  89326. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  89327. var _this = this;
  89328. if (accessor.sparse) {
  89329. throw new Error(context + ": Sparse accessors are not currently supported");
  89330. }
  89331. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  89332. if (!bufferView) {
  89333. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  89334. }
  89335. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  89336. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  89337. var data;
  89338. var byteOffset = accessor.byteOffset || 0;
  89339. var byteStride = bufferView.byteStride;
  89340. if (byteStride === 0) {
  89341. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  89342. }
  89343. try {
  89344. switch (accessor.componentType) {
  89345. case GLTF2.EComponentType.BYTE: {
  89346. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89347. break;
  89348. }
  89349. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  89350. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89351. break;
  89352. }
  89353. case GLTF2.EComponentType.SHORT: {
  89354. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89355. break;
  89356. }
  89357. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  89358. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89359. break;
  89360. }
  89361. case GLTF2.EComponentType.UNSIGNED_INT: {
  89362. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89363. break;
  89364. }
  89365. case GLTF2.EComponentType.FLOAT: {
  89366. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89367. break;
  89368. }
  89369. default: {
  89370. throw new Error(context + ": Invalid component type " + accessor.componentType);
  89371. }
  89372. }
  89373. }
  89374. catch (e) {
  89375. throw new Error(context + ": " + e);
  89376. }
  89377. onSuccess(data);
  89378. });
  89379. };
  89380. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  89381. byteOffset += data.byteOffset;
  89382. var targetLength = count * numComponents;
  89383. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  89384. return new typedArray(data.buffer, byteOffset, targetLength);
  89385. }
  89386. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  89387. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  89388. var targetBuffer = new typedArray(targetLength);
  89389. var sourceIndex = 0;
  89390. var targetIndex = 0;
  89391. while (targetIndex < targetLength) {
  89392. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  89393. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  89394. targetIndex++;
  89395. }
  89396. sourceIndex += elementStride;
  89397. }
  89398. return targetBuffer;
  89399. };
  89400. GLTFLoader.prototype._addPendingData = function (data) {
  89401. if (!this._renderReady) {
  89402. this._renderPendingCount++;
  89403. }
  89404. this._addLoaderPendingData(data);
  89405. };
  89406. GLTFLoader.prototype._removePendingData = function (data) {
  89407. var _this = this;
  89408. if (!this._renderReady) {
  89409. if (--this._renderPendingCount === 0) {
  89410. this._addLoaderPendingData(this);
  89411. this._compileMaterialsAsync(function () {
  89412. _this._compileShadowGeneratorsAsync(function () {
  89413. _this._removeLoaderPendingData(_this);
  89414. _this._renderReady = true;
  89415. _this._onRenderReady();
  89416. });
  89417. });
  89418. }
  89419. }
  89420. this._removeLoaderPendingData(data);
  89421. };
  89422. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  89423. this._loaderPendingCount++;
  89424. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  89425. var tracker = _a[_i];
  89426. tracker._addPendingData(data);
  89427. }
  89428. };
  89429. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  89430. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  89431. var tracker = _a[_i];
  89432. tracker._removePendingData(data);
  89433. }
  89434. if (--this._loaderPendingCount === 0) {
  89435. this._onComplete();
  89436. }
  89437. };
  89438. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  89439. var _this = this;
  89440. var tracker = new GLTFLoaderTracker(function () {
  89441. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  89442. onComplete();
  89443. });
  89444. this._loaderTrackers.push(tracker);
  89445. this._addLoaderPendingData(tracker);
  89446. action();
  89447. this._removeLoaderPendingData(tracker);
  89448. };
  89449. GLTFLoader.prototype._getDefaultMaterial = function () {
  89450. if (!this._defaultMaterial) {
  89451. var id = "__gltf_default";
  89452. var material = this._babylonScene.getMaterialByName(id);
  89453. if (!material) {
  89454. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  89455. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89456. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89457. material.metallic = 1;
  89458. material.roughness = 1;
  89459. }
  89460. this._defaultMaterial = material;
  89461. }
  89462. return this._defaultMaterial;
  89463. };
  89464. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  89465. var babylonMaterial = material.babylonMaterial;
  89466. // Ensure metallic workflow
  89467. babylonMaterial.metallic = 1;
  89468. babylonMaterial.roughness = 1;
  89469. var properties = material.pbrMetallicRoughness;
  89470. if (!properties) {
  89471. return;
  89472. }
  89473. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  89474. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  89475. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  89476. if (properties.baseColorTexture) {
  89477. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  89478. if (!texture) {
  89479. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  89480. }
  89481. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  89482. }
  89483. if (properties.metallicRoughnessTexture) {
  89484. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  89485. if (!texture) {
  89486. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  89487. }
  89488. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  89489. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  89490. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  89491. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  89492. }
  89493. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  89494. };
  89495. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  89496. if (material.babylonMaterial) {
  89497. assign(material.babylonMaterial, false);
  89498. return;
  89499. }
  89500. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  89501. return;
  89502. }
  89503. this._createPbrMaterial(material);
  89504. this._loadMaterialBaseProperties(context, material);
  89505. this._loadMaterialMetallicRoughnessProperties(context, material);
  89506. assign(material.babylonMaterial, true);
  89507. };
  89508. GLTFLoader.prototype._createPbrMaterial = function (material) {
  89509. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  89510. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89511. material.babylonMaterial = babylonMaterial;
  89512. };
  89513. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  89514. var babylonMaterial = material.babylonMaterial;
  89515. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  89516. if (material.doubleSided) {
  89517. babylonMaterial.backFaceCulling = false;
  89518. babylonMaterial.twoSidedLighting = true;
  89519. }
  89520. if (material.normalTexture) {
  89521. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  89522. if (!texture) {
  89523. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  89524. }
  89525. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  89526. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  89527. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  89528. if (material.normalTexture.scale != null) {
  89529. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  89530. }
  89531. }
  89532. if (material.occlusionTexture) {
  89533. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  89534. if (!texture) {
  89535. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  89536. }
  89537. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  89538. babylonMaterial.useAmbientInGrayScale = true;
  89539. if (material.occlusionTexture.strength != null) {
  89540. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  89541. }
  89542. }
  89543. if (material.emissiveTexture) {
  89544. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  89545. if (!texture) {
  89546. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  89547. }
  89548. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  89549. }
  89550. };
  89551. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  89552. var babylonMaterial = material.babylonMaterial;
  89553. var alphaMode = material.alphaMode || "OPAQUE";
  89554. switch (alphaMode) {
  89555. case "OPAQUE": {
  89556. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89557. break;
  89558. }
  89559. case "MASK": {
  89560. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  89561. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  89562. if (colorFactor) {
  89563. if (colorFactor[3] == 0) {
  89564. babylonMaterial.alphaCutOff = 1;
  89565. }
  89566. else {
  89567. babylonMaterial.alphaCutOff /= colorFactor[3];
  89568. }
  89569. }
  89570. if (babylonMaterial.albedoTexture) {
  89571. babylonMaterial.albedoTexture.hasAlpha = true;
  89572. }
  89573. break;
  89574. }
  89575. case "BLEND": {
  89576. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  89577. if (colorFactor) {
  89578. babylonMaterial.alpha = colorFactor[3];
  89579. }
  89580. if (babylonMaterial.albedoTexture) {
  89581. babylonMaterial.albedoTexture.hasAlpha = true;
  89582. babylonMaterial.useAlphaFromAlbedoTexture = true;
  89583. }
  89584. break;
  89585. }
  89586. default: {
  89587. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  89588. }
  89589. }
  89590. };
  89591. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  89592. var _this = this;
  89593. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  89594. if (!sampler) {
  89595. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  89596. }
  89597. this._loadSampler("#/samplers/" + sampler.index, sampler);
  89598. this._addPendingData(texture);
  89599. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  89600. _this._tryCatchOnError(function () {
  89601. _this._removePendingData(texture);
  89602. });
  89603. }, function (message) {
  89604. _this._tryCatchOnError(function () {
  89605. throw new Error(context + ": " + message);
  89606. });
  89607. });
  89608. if (texture.url) {
  89609. babylonTexture.updateURL(texture.url);
  89610. }
  89611. else if (texture.dataReadyObservable) {
  89612. texture.dataReadyObservable.add(function (texture) {
  89613. babylonTexture.updateURL(texture.url);
  89614. });
  89615. }
  89616. else {
  89617. texture.dataReadyObservable = new BABYLON.Observable();
  89618. texture.dataReadyObservable.add(function (texture) {
  89619. babylonTexture.updateURL(texture.url);
  89620. });
  89621. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  89622. if (!image_1) {
  89623. throw new Error(context + ": Failed to find source " + texture.source);
  89624. }
  89625. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  89626. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  89627. texture.dataReadyObservable.notifyObservers(texture);
  89628. texture.dataReadyObservable = undefined;
  89629. });
  89630. }
  89631. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  89632. babylonTexture.wrapU = sampler.wrapU;
  89633. babylonTexture.wrapV = sampler.wrapV;
  89634. babylonTexture.name = texture.name || "texture" + texture.index;
  89635. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  89636. return babylonTexture;
  89637. };
  89638. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  89639. if (sampler.noMipMaps != undefined) {
  89640. return;
  89641. }
  89642. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  89643. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  89644. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  89645. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  89646. };
  89647. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  89648. if (image.uri) {
  89649. this._loadUriAsync(context, image.uri, onSuccess);
  89650. }
  89651. else {
  89652. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  89653. if (!bufferView) {
  89654. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  89655. }
  89656. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  89657. }
  89658. };
  89659. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  89660. var _this = this;
  89661. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  89662. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  89663. return;
  89664. }
  89665. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  89666. throw new Error(context + ": Uri '" + uri + "' is invalid");
  89667. }
  89668. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  89669. _this._tryCatchOnError(function () {
  89670. onSuccess(new Uint8Array(data));
  89671. });
  89672. }, function (event) {
  89673. _this._tryCatchOnError(function () {
  89674. if (request && !_this._renderReady) {
  89675. request._lengthComputable = event.lengthComputable;
  89676. request._loaded = event.loaded;
  89677. request._total = event.total;
  89678. _this._onProgress();
  89679. }
  89680. });
  89681. }, this._babylonScene.database, true, function (request, exception) {
  89682. _this._tryCatchOnError(function () {
  89683. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  89684. });
  89685. });
  89686. this._requests.push(request);
  89687. };
  89688. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  89689. if (this._disposed) {
  89690. return;
  89691. }
  89692. try {
  89693. handler();
  89694. }
  89695. catch (e) {
  89696. BABYLON.Tools.Error("glTF Loader: " + e.message);
  89697. if (this._errorCallback) {
  89698. this._errorCallback(e.message, e);
  89699. }
  89700. this.dispose();
  89701. }
  89702. };
  89703. GLTFLoader._AssignIndices = function (array) {
  89704. if (array) {
  89705. for (var index = 0; index < array.length; index++) {
  89706. array[index].index = index;
  89707. }
  89708. }
  89709. };
  89710. GLTFLoader._GetProperty = function (array, index) {
  89711. if (!array || index == undefined || !array[index]) {
  89712. return null;
  89713. }
  89714. return array[index];
  89715. };
  89716. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  89717. // Set defaults if undefined
  89718. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  89719. switch (mode) {
  89720. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  89721. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  89722. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  89723. default:
  89724. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  89725. return BABYLON.Texture.WRAP_ADDRESSMODE;
  89726. }
  89727. };
  89728. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  89729. // Set defaults if undefined
  89730. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  89731. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  89732. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  89733. switch (minFilter) {
  89734. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  89735. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  89736. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  89737. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  89738. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  89739. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89740. default:
  89741. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89742. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89743. }
  89744. }
  89745. else {
  89746. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  89747. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  89748. }
  89749. switch (minFilter) {
  89750. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  89751. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  89752. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89753. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  89754. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  89755. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  89756. default:
  89757. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89758. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89759. }
  89760. }
  89761. };
  89762. GLTFLoader._GetNumComponents = function (context, type) {
  89763. switch (type) {
  89764. case "SCALAR": return 1;
  89765. case "VEC2": return 2;
  89766. case "VEC3": return 3;
  89767. case "VEC4": return 4;
  89768. case "MAT2": return 4;
  89769. case "MAT3": return 9;
  89770. case "MAT4": return 16;
  89771. }
  89772. throw new Error(context + ": Invalid type " + type);
  89773. };
  89774. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  89775. var _this = this;
  89776. if (this.useClipPlane) {
  89777. babylonMaterial.forceCompilation(babylonMesh, function () {
  89778. babylonMaterial.forceCompilation(babylonMesh, function () {
  89779. _this._tryCatchOnError(onSuccess);
  89780. }, { clipPlane: true });
  89781. });
  89782. }
  89783. else {
  89784. babylonMaterial.forceCompilation(babylonMesh, function () {
  89785. _this._tryCatchOnError(onSuccess);
  89786. });
  89787. }
  89788. };
  89789. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  89790. if (!this.compileMaterials || !this._gltf.materials) {
  89791. onSuccess();
  89792. return;
  89793. }
  89794. var meshes = this._getMeshes();
  89795. var remaining = 0;
  89796. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  89797. var mesh = meshes_1[_i];
  89798. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89799. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  89800. var subMaterial = _b[_a];
  89801. if (subMaterial) {
  89802. remaining++;
  89803. }
  89804. }
  89805. }
  89806. else if (mesh.material) {
  89807. remaining++;
  89808. }
  89809. }
  89810. if (remaining === 0) {
  89811. onSuccess();
  89812. return;
  89813. }
  89814. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  89815. var mesh = meshes_2[_c];
  89816. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89817. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  89818. var subMaterial = _e[_d];
  89819. if (subMaterial) {
  89820. this._compileMaterialAsync(subMaterial, mesh, function () {
  89821. if (--remaining === 0) {
  89822. onSuccess();
  89823. }
  89824. });
  89825. }
  89826. }
  89827. }
  89828. else if (mesh.material) {
  89829. this._compileMaterialAsync(mesh.material, mesh, function () {
  89830. if (--remaining === 0) {
  89831. onSuccess();
  89832. }
  89833. });
  89834. }
  89835. }
  89836. };
  89837. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  89838. var _this = this;
  89839. if (!this.compileShadowGenerators) {
  89840. onSuccess();
  89841. return;
  89842. }
  89843. var lights = this._babylonScene.lights;
  89844. var remaining = 0;
  89845. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  89846. var light = lights_1[_i];
  89847. var generator = light.getShadowGenerator();
  89848. if (generator) {
  89849. remaining++;
  89850. }
  89851. }
  89852. if (remaining === 0) {
  89853. onSuccess();
  89854. return;
  89855. }
  89856. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  89857. var light = lights_2[_a];
  89858. var generator = light.getShadowGenerator();
  89859. if (generator) {
  89860. generator.forceCompilation(function () {
  89861. if (--remaining === 0) {
  89862. _this._tryCatchOnError(onSuccess);
  89863. }
  89864. });
  89865. }
  89866. }
  89867. };
  89868. GLTFLoader.prototype._abortRequests = function () {
  89869. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89870. var request = _a[_i];
  89871. request.abort();
  89872. }
  89873. this._requests.length = 0;
  89874. };
  89875. GLTFLoader.prototype._releaseResources = function () {
  89876. if (this._gltf.textures) {
  89877. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  89878. var texture = _a[_i];
  89879. if (texture.url) {
  89880. URL.revokeObjectURL(texture.url);
  89881. texture.url = undefined;
  89882. }
  89883. }
  89884. }
  89885. };
  89886. GLTFLoader.Extensions = {};
  89887. return GLTFLoader;
  89888. }());
  89889. GLTF2.GLTFLoader = GLTFLoader;
  89890. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  89891. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89892. })(BABYLON || (BABYLON = {}));
  89893. //# sourceMappingURL=babylon.glTFLoader.js.map
  89894. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89895. var BABYLON;
  89896. (function (BABYLON) {
  89897. var GLTF2;
  89898. (function (GLTF2) {
  89899. /**
  89900. * Utils functions for GLTF
  89901. */
  89902. var GLTFUtils = /** @class */ (function () {
  89903. function GLTFUtils() {
  89904. }
  89905. /**
  89906. * If the uri is a base64 string
  89907. * @param uri: the uri to test
  89908. */
  89909. GLTFUtils.IsBase64 = function (uri) {
  89910. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  89911. };
  89912. /**
  89913. * Decode the base64 uri
  89914. * @param uri: the uri to decode
  89915. */
  89916. GLTFUtils.DecodeBase64 = function (uri) {
  89917. var decodedString = atob(uri.split(",")[1]);
  89918. var bufferLength = decodedString.length;
  89919. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  89920. for (var i = 0; i < bufferLength; i++) {
  89921. bufferView[i] = decodedString.charCodeAt(i);
  89922. }
  89923. return bufferView.buffer;
  89924. };
  89925. GLTFUtils.ValidateUri = function (uri) {
  89926. return (uri.indexOf("..") === -1);
  89927. };
  89928. return GLTFUtils;
  89929. }());
  89930. GLTF2.GLTFUtils = GLTFUtils;
  89931. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89932. })(BABYLON || (BABYLON = {}));
  89933. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89934. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89935. var BABYLON;
  89936. (function (BABYLON) {
  89937. var GLTF2;
  89938. (function (GLTF2) {
  89939. var GLTFLoaderExtension = /** @class */ (function () {
  89940. function GLTFLoaderExtension() {
  89941. this.enabled = true;
  89942. }
  89943. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  89944. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  89945. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  89946. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  89947. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  89948. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  89949. var _this = this;
  89950. if (!property.extensions) {
  89951. return false;
  89952. }
  89953. var extension = property.extensions[this.name];
  89954. if (!extension) {
  89955. return false;
  89956. }
  89957. // Clear out the extension before executing the action to avoid recursing into the same property.
  89958. property.extensions[this.name] = undefined;
  89959. action(context + "extensions/" + this.name, extension, function () {
  89960. // Restore the extension after completing the action.
  89961. property.extensions[_this.name] = extension;
  89962. });
  89963. return true;
  89964. };
  89965. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  89966. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  89967. };
  89968. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  89969. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  89970. };
  89971. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  89972. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  89973. };
  89974. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  89975. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  89976. };
  89977. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  89978. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  89979. };
  89980. GLTFLoaderExtension._ApplyExtensions = function (action) {
  89981. var extensions = GLTFLoaderExtension._Extensions;
  89982. if (!extensions) {
  89983. return false;
  89984. }
  89985. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  89986. var extension = extensions_1[_i];
  89987. if (extension.enabled && action(extension)) {
  89988. return true;
  89989. }
  89990. }
  89991. return false;
  89992. };
  89993. //
  89994. // Utilities
  89995. //
  89996. GLTFLoaderExtension._Extensions = [];
  89997. return GLTFLoaderExtension;
  89998. }());
  89999. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  90000. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90001. })(BABYLON || (BABYLON = {}));
  90002. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90003. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  90004. var BABYLON;
  90005. (function (BABYLON) {
  90006. var GLTF2;
  90007. (function (GLTF2) {
  90008. var Extensions;
  90009. (function (Extensions) {
  90010. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  90011. var MSFTLOD = /** @class */ (function (_super) {
  90012. __extends(MSFTLOD, _super);
  90013. function MSFTLOD() {
  90014. var _this = _super !== null && _super.apply(this, arguments) || this;
  90015. /**
  90016. * Specify the minimal delay between LODs in ms (default = 250)
  90017. */
  90018. _this.Delay = 250;
  90019. return _this;
  90020. }
  90021. Object.defineProperty(MSFTLOD.prototype, "name", {
  90022. get: function () {
  90023. return "MSFT_lod";
  90024. },
  90025. enumerable: true,
  90026. configurable: true
  90027. });
  90028. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  90029. return this._loadExtension(context, node, function (context, extension, onComplete) {
  90030. for (var i = extension.ids.length - 1; i >= 0; i--) {
  90031. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  90032. if (!lodNode) {
  90033. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  90034. }
  90035. loader._traverseNode(context, lodNode, action, parentNode);
  90036. }
  90037. loader._traverseNode(context, node, action, parentNode);
  90038. onComplete();
  90039. });
  90040. };
  90041. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  90042. var _this = this;
  90043. return this._loadExtension(context, node, function (context, extension, onComplete) {
  90044. var nodes = [node];
  90045. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  90046. var index = _a[_i];
  90047. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  90048. if (!lodNode) {
  90049. throw new Error(context + ": Failed to find node " + index);
  90050. }
  90051. nodes.push(lodNode);
  90052. }
  90053. loader._addLoaderPendingData(node);
  90054. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  90055. loader._removeLoaderPendingData(node);
  90056. onComplete();
  90057. });
  90058. });
  90059. };
  90060. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  90061. var _this = this;
  90062. loader._whenAction(function () {
  90063. loader._loadNode(context, nodes[index]);
  90064. }, function () {
  90065. if (index !== nodes.length - 1) {
  90066. var previousNode = nodes[index + 1];
  90067. previousNode.babylonMesh.setEnabled(false);
  90068. }
  90069. if (index === 0) {
  90070. onComplete();
  90071. return;
  90072. }
  90073. setTimeout(function () {
  90074. loader._tryCatchOnError(function () {
  90075. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  90076. });
  90077. }, _this.Delay);
  90078. });
  90079. };
  90080. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  90081. var _this = this;
  90082. return this._loadExtension(context, material, function (context, extension, onComplete) {
  90083. var materials = [material];
  90084. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  90085. var index = _a[_i];
  90086. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  90087. if (!lodMaterial) {
  90088. throw new Error(context + ": Failed to find material " + index);
  90089. }
  90090. materials.push(lodMaterial);
  90091. }
  90092. loader._addLoaderPendingData(material);
  90093. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  90094. loader._removeLoaderPendingData(material);
  90095. onComplete();
  90096. });
  90097. });
  90098. };
  90099. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  90100. var _this = this;
  90101. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  90102. if (index === materials.length - 1) {
  90103. assign(babylonMaterial, isNew);
  90104. // Load the next LOD when the loader is ready to render.
  90105. loader._executeWhenRenderReady(function () {
  90106. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  90107. });
  90108. }
  90109. else {
  90110. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  90111. assign(babylonMaterial, isNew);
  90112. if (index === 0) {
  90113. onComplete();
  90114. }
  90115. else {
  90116. setTimeout(function () {
  90117. loader._tryCatchOnError(function () {
  90118. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  90119. });
  90120. }, _this.Delay);
  90121. }
  90122. });
  90123. }
  90124. });
  90125. };
  90126. return MSFTLOD;
  90127. }(GLTF2.GLTFLoaderExtension));
  90128. Extensions.MSFTLOD = MSFTLOD;
  90129. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  90130. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  90131. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90132. })(BABYLON || (BABYLON = {}));
  90133. //# sourceMappingURL=MSFT_lod.js.map
  90134. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  90135. var BABYLON;
  90136. (function (BABYLON) {
  90137. var GLTF2;
  90138. (function (GLTF2) {
  90139. var Extensions;
  90140. (function (Extensions) {
  90141. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  90142. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  90143. function KHRMaterialsPbrSpecularGlossiness() {
  90144. return _super !== null && _super.apply(this, arguments) || this;
  90145. }
  90146. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  90147. get: function () {
  90148. return "KHR_materials_pbrSpecularGlossiness";
  90149. },
  90150. enumerable: true,
  90151. configurable: true
  90152. });
  90153. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  90154. var _this = this;
  90155. return this._loadExtension(context, material, function (context, extension, onComplete) {
  90156. loader._createPbrMaterial(material);
  90157. loader._loadMaterialBaseProperties(context, material);
  90158. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  90159. assign(material.babylonMaterial, true);
  90160. onComplete();
  90161. });
  90162. };
  90163. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  90164. var babylonMaterial = material.babylonMaterial;
  90165. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  90166. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  90167. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  90168. if (properties.diffuseTexture) {
  90169. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  90170. if (!texture) {
  90171. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  90172. }
  90173. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  90174. }
  90175. if (properties.specularGlossinessTexture) {
  90176. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  90177. if (!texture) {
  90178. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  90179. }
  90180. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  90181. babylonMaterial.reflectivityTexture.hasAlpha = true;
  90182. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  90183. }
  90184. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  90185. };
  90186. return KHRMaterialsPbrSpecularGlossiness;
  90187. }(GLTF2.GLTFLoaderExtension));
  90188. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  90189. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  90190. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  90191. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90192. })(BABYLON || (BABYLON = {}));
  90193. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  90194. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  90195. var BABYLON;
  90196. (function (BABYLON) {
  90197. var GLTF2;
  90198. (function (GLTF2) {
  90199. var Extensions;
  90200. (function (Extensions) {
  90201. var KHRLights = /** @class */ (function (_super) {
  90202. __extends(KHRLights, _super);
  90203. function KHRLights() {
  90204. return _super !== null && _super.apply(this, arguments) || this;
  90205. }
  90206. Object.defineProperty(KHRLights.prototype, "name", {
  90207. get: function () {
  90208. return "KHR_lights";
  90209. },
  90210. enumerable: true,
  90211. configurable: true
  90212. });
  90213. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  90214. if (lightInfo.color) {
  90215. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  90216. }
  90217. else {
  90218. light.diffuse.copyFromFloats(1, 1, 1);
  90219. }
  90220. if (lightInfo.intensity !== undefined) {
  90221. light.intensity = lightInfo.intensity;
  90222. }
  90223. else {
  90224. light.intensity = 1;
  90225. }
  90226. };
  90227. KHRLights.prototype._loadScene = function (loader, context, scene) {
  90228. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  90229. if (extension.light >= 0 && loader._gltf.extensions) {
  90230. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  90231. if (lightInfo.type !== 'ambient') {
  90232. return;
  90233. }
  90234. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  90235. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  90236. }
  90237. onComplete();
  90238. });
  90239. };
  90240. KHRLights.prototype._loadNode = function (loader, context, node) {
  90241. var _this = this;
  90242. return this._loadExtension(context, node, function (context, extension, onComplete) {
  90243. if (extension.light >= 0 && loader._gltf.extensions) {
  90244. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  90245. var name_1 = node.name || 'Light';
  90246. var matrix = void 0;
  90247. if (node.matrix) {
  90248. matrix = BABYLON.Matrix.FromArray(node.matrix);
  90249. }
  90250. else {
  90251. matrix = BABYLON.Matrix.Identity();
  90252. }
  90253. var direction = new BABYLON.Vector3(0, 0, 1);
  90254. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  90255. var rotationMatrix = matrix.getRotationMatrix();
  90256. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  90257. }
  90258. var light = void 0;
  90259. if (lightInfo.type == 'directional') {
  90260. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  90261. }
  90262. else {
  90263. var position = matrix.getTranslation();
  90264. if (lightInfo.type == 'spot') {
  90265. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  90266. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  90267. }
  90268. else {
  90269. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  90270. }
  90271. }
  90272. _this.applyCommonProperties(light, lightInfo);
  90273. extension.babylonLight = light;
  90274. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  90275. if (node.children) {
  90276. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  90277. var index = _a[_i];
  90278. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  90279. if (!childNode) {
  90280. throw new Error(context + ": Failed to find child node " + index);
  90281. }
  90282. loader._loadNode("#/nodes/" + index, childNode);
  90283. }
  90284. }
  90285. }
  90286. onComplete();
  90287. });
  90288. };
  90289. KHRLights.prototype._loadRoot = function (loader, context, root) {
  90290. return this._loadExtension(context, root, function (context, extension, onComplete) {
  90291. extension.lights.forEach(function (light, idx) {
  90292. light.index = idx;
  90293. });
  90294. onComplete();
  90295. });
  90296. };
  90297. return KHRLights;
  90298. }(GLTF2.GLTFLoaderExtension));
  90299. Extensions.KHRLights = KHRLights;
  90300. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  90301. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  90302. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90303. })(BABYLON || (BABYLON = {}));
  90304. //# sourceMappingURL=KHR_lights.js.map
  90305. (function universalModuleDefinition(root, factory) {
  90306. var f = factory();
  90307. if (root && root["BABYLON"]) {
  90308. return;
  90309. }
  90310. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  90311. globalObject["BABYLON"] = f;
  90312. if(typeof exports === 'object' && typeof module === 'object')
  90313. module.exports = f;
  90314. else if(typeof define === 'function' && define.amd)
  90315. define(["BABYLON"], factory);
  90316. else if(typeof exports === 'object')
  90317. exports["BABYLON"] = f;
  90318. else {
  90319. root["BABYLON"] = f;
  90320. }
  90321. })(this, function() {
  90322. return BABYLON;
  90323. });